--更新升级信息
if NOT exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[edition]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[edition] (
	[edition] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,  ---补丁或定制或升级
	[pubdate] [varchar] (10) COLLATE Chinese_PRC_CI_AS NOT NULL ,   -- 日期
	[Comment] [varchar] (2000) COLLATE Chinese_PRC_CI_AS NOT NULL , --详细描述
	[id] [int] IDENTITY (1, 1) NOT NULL 
) ON [PRIMARY]

ALTER TABLE [dbo].[edition] ADD 
	CONSTRAINT [DF_edition_edition] DEFAULT ('') FOR [edition],
	CONSTRAINT [DF_edition_pubdate] DEFAULT ('') FOR [pubdate],
	CONSTRAINT [DF_edition_Comment] DEFAULT ('') FOR [Comment]
END
GO

if not exists(select * from edition)
	insert into edition(edition,pubdate,comment)
	select subvalue,right(subvalue,10),'原始版本' from sysdata where subname='IssueVersion'
GO

-- 处理升级记录
declare @edition varchar(200)
declare @Comment varchar(200)
--补丁、定制、升级
SET @edition='补丁'
--详细描述
SET @Comment='服装.NET II V6.66补丁-20141121'
insert into edition(edition,pubdate,comment) values 
(@edition,convert(varchar(4),year(getdate()))+'.'+right('0'+ltrim(convert(varchar(2),month(getdate()))),2)+'.'+right('0'+ltrim(convert(varchar(2),day(getdate()))),2),@Comment)
GO
---------------------------------------------------------------------------------------------

update sysdata set SubValue ='管家婆服装.netII 6.66-2013.05.06' where SubName ='IssueVersion'
GO

--只有卓一这个客户才是店账通可修改，其它要通过改数据库配置才能改
if exists(select * from fzbsxiwaztinfo where ztname='卓一')
BEGIN
	IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'DZTEdit')
	INSERT INTO dbo.SysData( SubName, SubValue, SubComment )
	VALUES  ('DZTEdit','1','店账通单据可否修改 1 可修改其它不可修改cqh2014-11-21')
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT 1 FROM sysdata WHERE SubName = 'DZTEdit')
	INSERT INTO dbo.SysData( SubName, SubValue, SubComment )
	VALUES  ('DZTEdit','0','店账通单据可否修改 1 可修改其它不可修改cqh2014-11-21')
END
go

/******************************************20130506********************************************/

--基本信息缓存表
IF NOT EXISTS(SELECT * FROM dbo.XW_BaseUpdateTag WHERE BaseType='PtypeAttribute')
BEGIN
	INSERT INTO dbo.XW_BaseUpdateTag( BaseType, UpdateTag ) VALUES  ( 'PtypeAttribute', 0)
END
GO
IF NOT EXISTS(SELECT * FROM dbo.XW_BaseUpdateTag WHERE BaseType='PtypeBar')
BEGIN
	INSERT INTO dbo.XW_BaseUpdateTag( BaseType, UpdateTag ) VALUES  ( 'PtypeBar', 0)
END
GO
IF NOT EXISTS(SELECT * FROM dbo.XW_BaseUpdateTag WHERE BaseType='PtypePrice')
BEGIN
	INSERT INTO dbo.XW_BaseUpdateTag( BaseType, UpdateTag ) VALUES  ( 'PtypePrice', 0)
END
GO
--商品信息的修改
IF Not Exists(select * from dbo.syscolumns where id = object_id(N'[dbo].[Ptype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1 and name = 'UpdateTagAttribute')
Begin
	ALTER TABLE [dbo].Ptype ADD UpdateTagAttribute INT NOT NULL DEFAULT 0 --商品属性更新最大数
End
GO
IF Not Exists(select * from dbo.syscolumns where id = object_id(N'[dbo].[Ptype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1 and name = 'UpdateTagBar')
Begin
	ALTER TABLE [dbo].Ptype ADD UpdateTagBar INT NOT NULL DEFAULT 0 --商品条码更新最大数
End
GO
IF Not Exists(select * from dbo.syscolumns where id = object_id(N'[dbo].[Ptype]') and OBJECTPROPERTY(id, N'IsUserTable') = 1 and name = 'UpdateTagPrice')
Begin
	ALTER TABLE [dbo].Ptype ADD UpdateTagPrice INT NOT NULL DEFAULT 0 --商品价格更新最大数
End
GO

--  ********************************************************************************************  actionlist--  *****************************************
-- 生成明细权限
TRUNCATE TABLE ActionList
--IF NOT EXISTS(SELECT * FROM ActionList where moduleid like '11%')
BEGIN
	TRUNCATE TABLE ActionList
	--商品信息
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010101','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010101','002','分类',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010101','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010101','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010101','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010101','029','库存详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010101','095','商品导入',1,1,1,1,'','',0)
	--颜色
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010102','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010102','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010102','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010102','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010102','093','颜色信息导入',1,1,1,1,'','',0)
	--颜色组
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010103','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010103','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010103','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010103','005','打印',1,1,1,1,'','',0)
	--尺码
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010104','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010104','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010104','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010104','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010104','093','尺码信息导入',1,1,1,1,'','',0)
	--尺码组
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010105','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010105','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010105','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010105','005','打印',1,1,1,1,'','',0)
	--配码
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010110','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010110','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010110','004','删除',1,1,1,1,'','',0)	
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010110','005','打印',1,1,1,1,'','',0)
	--辅助属性类型
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010106','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010106','003','修改',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010106','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010106','005','打印',1,1,1,1,'','',0)
	--辅助属性
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010107','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010107','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010107','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010107','005','打印',1,1,1,1,'','',0)
	--条码对照表
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010108','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010108','068','编辑条码',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010108','069','清除本行对照码',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010108','070','清除该商品所有对照码',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010108','085','单据中查看VIP信息',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010108','092','对照码导入',1,1,1,1,'','',0)
	--条码打印
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010109','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010109','155','修改流水码',1,1,1,1,'','',0)

	--供应商
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010201','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010201','002','分类',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010201','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010201','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010201','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010201','107','供应商导入',1,1,1,1,'','',0)
	--客户
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010202','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010202','002','分类',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010202','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010202','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010202','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010202','108','客户导入',1,1,1,1,'','',0)
	--代销单位
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010203','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010203','002','分类',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010203','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010203','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010203','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010203','111','代销单位导入',1,1,1,1,'','',0)
	--分支机构
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0103','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0103','002','分类',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0103','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0103','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0103','005','打印',1,1,1,1,'','',0)
	--存货仓库
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0104','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0104','002','分类',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0104','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0104','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0104','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0104','109','仓库导入',1,1,1,1,'','',0)
	--会计科目
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010502','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010502','002','分类',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010502','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010502','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010502','005','打印',1,1,1,1,'','',0)
	--职员
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0106','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0106','002','分类',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0106','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0106','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0106','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0106','110','职员导入',1,1,1,1,'','',0)
	--部门
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0107','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0107','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0107','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0107','005','打印',1,1,1,1,'','',0)
	--业务类型 - 发货类型
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011201','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011201','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011201','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011201','005','打印',1,1,1,1,'','',0)
	--业务类型 - 收货类型
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011202','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011202','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011202','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011202','005','打印',1,1,1,1,'','',0)

	--010111','条码方案
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010111','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010111','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010111','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010111','005','打印',1,1,1,1,'','',0)




	--业务类型 - 退货类型
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011203','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011203','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011203','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011203','005','打印',1,1,1,1,'','',0)
	--业务类型 - 出库类型
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011204','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011204','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011204','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011204','005','打印',1,1,1,1,'','',0)
	--业务类型 - 入库类型
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011205','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011205','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011205','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011205','005','打印',1,1,1,1,'','',0)
	
	--业务类型 - 发货类型(加盟)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100701','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100701','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100701','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100701','005','打印',1,1,1,1,'','',0)
	--业务类型 - 退货类型(加盟)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100702','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100702','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100702','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100702','005','打印',1,1,1,1,'','',0)
	--业务类型 - 出库类型(加盟)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100703','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100703','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100703','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100703','005','打印',1,1,1,1,'','',0)
	--业务类型 - 入库类型(加盟)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100704','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100704','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100704','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('01100704','005','打印',1,1,1,1,'','',0)
	--库存期初
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010801','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010801','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010801','011','成本查看',1,1,1,1,'','',0)
	--应收期初
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010802','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010802','005','打印',1,1,1,1,'','',0)
	--应付期初
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010803','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010803','005','打印',1,1,1,1,'','',0)
	--现金银行期初
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010804','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010804','005','打印',1,1,1,1,'','',0)
	--账务期初
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010805','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('010805','005','打印',1,1,1,1,'','',0)
	--期初资产负债表
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0109','005','打印',1,1,1,1,'','',0)


	--存货仓库
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011001','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011001','002','分类',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011001','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011001','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011001','005','打印',1,1,1,1,'','',0)
	--客户
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011002','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011002','002','分类',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011002','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011002','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011002','005','打印',1,1,1,1,'','',0)
	--职员
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011003','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011003','002','分类',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011003','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011003','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011003','005','打印',1,1,1,1,'','',0)
	--部门
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011004','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011004','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011004','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011004','005','打印',1,1,1,1,'','',0)
	--会计科目
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011006','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011006','002','分类',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011006','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011006','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('011006','005','打印',1,1,1,1,'','',0)
	
	--采购订单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0201','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0201','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0201','009','修改单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0201','010','修改折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0201','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0201','081','保存订单',1,1,1,1,'','',0)
	
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0201','157','选择单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0201','158','选择折扣',1,1,1,1,'','',0)
	
	--采购入库单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0202','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0202','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0202','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0202','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0202','009','修改单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0202','157','选择单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0202','010','修改折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0202','158','选择折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0202','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0202','067','存为草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0202','137','捡货',1,1,1,1,'','',0)
	
	
	--采购退货单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0203','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0203','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0203','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0203','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0203','009','修改单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0203','010','修改折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0203','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0203','067','存为草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0203','137','捡货',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0203','157','选择单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0203','158','选择折扣',1,1,1,1,'','',0)


	--商品采购统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021107','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021107','011','成本查看',1,1,1,1,'','',0)
	--供应商供货统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021109','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021109','011','成本查看',1,1,1,1,'','',0)
	--商品采购分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021110','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021110','011','成本查看',1,1,1,1,'','',0)
	--采购汇总分析	
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021112','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021112','011','成本查看',1,1,1,1,'','',0)

	--021106','机构采购分布汇总统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021106','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021106','011','成本查看',1,1,1,1,'','',0)

	--销售订单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0301','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0301','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0301','009','修改单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0301','010','修改折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0301','081','保存订单',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0301','157','选择单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0301','158','选择折扣',1,1,1,1,'','',0)
	
	--销售出库单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0302','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0302','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0302','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0302','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0302','009','修改单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0302','010','修改折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0302','067','存为草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0302','137','捡货',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0302','157','选择单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0302','158','选择折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0302','144','调订单界面打印 ',1,1,1,1,'','',0)
	--销售退货单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0303','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0303','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0303','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0303','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0303','009','修改单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0303','010','修改折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0303','067','存为草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0303','137','捡货',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0303','157','选择单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0303','158','选择折扣',1,1,1,1,'','',0)
	--销售换货单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0304','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0304','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0304','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0304','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0304','051','修改换出单单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0304','052','修改换出单折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0304','053','修改换入单单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0304','054','修改换入单折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0304','067','存为草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0304','157','选择换出单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0304','158','选择换出折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0304','159','选择换入单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0304','160','选择换入折扣',1,1,1,1,'','',0)
	
	--职员业务统计
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030501','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030501','011','成本查看',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030501','060','关联客户详情',1,1,1,1,'','',0)


	--'1601','商品进销存分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1601','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1601','011','成本查看',1,1,1,1,'','',0)

	--1611','赠品分析'
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1611','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1611','011','成本查看',1,1,1,1,'','',0)

	--销售综合分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1605','005','打印',1,1,1,1,'','',0)

	--客户业务统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1609','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1609','011','成本查看',1,1,1,1,'','',0)

	--1615','机构盈利统计分析'
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1615','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1615','011','成本查看',1,1,1,1,'','',0)

	--1616','机构销售分布汇总统计'
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1616','005','打印',1,1,1,1,'','',0)
	
	--1617','机构收款统计'
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1617','005','打印',1,1,1,1,'','',0)
	
	--1606 销售排行榜
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1606','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1606','011','成本查看',1,1,1,1,'','',0)

	--1607','商品畅滞销分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1607','005','打印',1,1,1,1,'','',0)


	--商品销售明细表
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030601','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030601','011','成本查看',1,1,1,1,'','',0)
	--销售状况表
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030602','005','打印',1,1,1,1,'','',0)

	--销售综合分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030620','005','打印',1,1,1,1,'','',0)

	--销售成本分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030621','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030621','011','成本查看',1,1,1,1,'','',0)




	--商品销售分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030603','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030603','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030603','061','客户销售详情权限',1,1,1,1,'','',0)
	--客户销售分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030604','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030604','011','成本查看',1,1,1,1,'','',0)
	--仓库销售分布
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030605','005','打印',1,1,1,1,'','',0)
	--销售年月日统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1608','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1608','011','成本查看',1,1,1,1,'','',0)
	--商品动销比分析报表
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1603','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1603','011','成本查看',1,1,1,1,'','',0)
	--商品售罄率分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030611','005','打印',1,1,1,1,'','',0)
	--客户上货情况分析表
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030612','005','打印',1,1,1,1,'','',0)
	
	--零售收银报表 
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0405','005','打印',1,1,1,1,'','',0)

	-- 零售收银设置 
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0402','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0402','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0402','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0402','005','打印',1,1,1,1,'','',0)




	--单品分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1604','005','打印',1,1,1,1,'','',0)
	--畅滞销分析
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030608','005','打印',1,1,1,1,'','',0)
	--客户退换货查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1610','005','打印',1,1,1,1,'','',0)
	--商品销售排行榜
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030701','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030701','011','成本查看',1,1,1,1,'','',0)
	--客户销售排行榜
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030702','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030702','011','成本查看',1,1,1,1,'','',0)
	--仓库销售排行榜
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030703','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030703','011','成本查看',1,1,1,1,'','',0)
	--职员销售排行榜
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030704','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030704','011','成本查看',1,1,1,1,'','',0)
	--颜色销售排行榜
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030705','005','打印',1,1,1,1,'','',0)
	--尺码销售排行榜
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030706','005','打印',1,1,1,1,'','',0)
	--商品颜色尺码销售排行榜
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030707','005','打印',1,1,1,1,'','',0)
	--销售收款统计-
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1613','005','打印',1,1,1,1,'','',0)
	--经营报表
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1614','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1614','011','成本查看',1,1,1,1,'','',0)
	
 	--零售计划配置
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041201','005','打印',1,1,1,1,'','',0)
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041201','001','新增',1,1,1,1,'','',0)
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041201','003','修改',1,1,1,1,'','',0)
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041201','004','删除',1,1,1,1,'','',0)
 	--零售计划单
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041202','005','打印',1,1,1,1,'','',0)
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041202','013','保存',1,1,1,1,'','',0)
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041202','134','审核并保存',1,1,1,1,'','',0)
 	--零售计划单查询
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041203','005','打印',1,1,1,1,'','',0)
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041203','003','修改',1,1,1,1,'','',0)
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041203','004','删除',1,1,1,1,'','',0)
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041203','042','审核',1,1,1,1,'','',0)
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041203','020','反审核',1,1,1,1,'','',0)
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041203','135','终止',1,1,1,1,'','',0)
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041203','026','恢复',1,1,1,1,'','',0)
 	
 	--041204','零售计划完成统计
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041204','005','打印',1,1,1,1,'','',0)
 	
	--商品进销存统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030801','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030801','011','成本查看',1,1,1,1,'','',0)
	--仓库进销存统计
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030802','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030802','011','成本查看',1,1,1,1,'','',0)
	--零售单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0401','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0401','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0401','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0401','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0401','009','修改单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0401','010','修改折扣',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0401','065','修改收款账户金额',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0401','067','存为草稿',1,1,1,1,'','',0)
	
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0401','157','选择单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0401','158','选择折扣',1,1,1,1,'','',0)
	
	
	
-- 	--零售单明细分析
-- 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041001','005','打印',1,1,1,1,'','',0)
-- 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041001','136','调阅单据',1,1,1,1,'','',0)
-- 	--商品零售分析
-- 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041002','005','打印',1,1,1,1,'','',0)
	--商品零售综合分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041003','005','打印',1,1,1,1,'','',0)
	--商店商品售罄率分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041004','005','打印',1,1,1,1,'','',0)
	--商店零售分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041005','005','打印',1,1,1,1,'','',0)
	--商店sku动销比分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041006','005','打印',1,1,1,1,'','',0)

	--('','促销赠品分析'	
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('04091701','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('04091701','011','成本查看',1,1,1,1,'','',0)
	--POS销存动态跟踪
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041011','005','打印',1,1,1,1,'','',0)


	--041012','机构促销分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('04091702','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('04091702','011','成本查看',1,1,1,1,'','',0)

	--零售对比分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041007','005','打印',1,1,1,1,'','',0)
	
	--供应商供货准时分析
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021104','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021104','011','成本查看',1,1,1,1,'','',0)
	
	--0412','价格变迁零售统计'
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0413','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0413','011','成本查看',1,1,1,1,'','',0)
	
	--'041009','商品零售分析'
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041009','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('041009','011','成本查看',1,1,1,1,'','',0)
	
	
	--021105','供应商供货对照表
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021105','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021105','011','成本查看',1,1,1,1,'','',0)
	
	--'030618','销售明细分析'
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030618','005','打印',1,1,1,1,'','',0)
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030618','103','原始单据',1,1,1,1,'','',0)

	
	--促销管理相关
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040901','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040902','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('04090305','005','打印',1,1,1,1,'','',0)

	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040904','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040905','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040906','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040907','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040903','116','促销方案管理--复制',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040903','013','促销方案管理--修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040903','004','促销方案管理--删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040903','042','促销方案管理--审核',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040903','104','促销方案管理--终止',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040903','117','促销方案管理--恢复',1,1,1,1,'','',0)

	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040903','118','促销方案管理--特价促销',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040903','119','促销方案管理--赠品促销',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040903','120','促销方案管理--手工促销',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040903','121','促销方案管理--组合促销',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040903','122','促销方案管理--促销管理',1,1,1,1,'','',0)



	--代销零售单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0408','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0408','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0408','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0408','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0408','009','修改单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0408','010','修改折扣',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0408','065','修改收款账户金额',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0408','067','存为草稿',1,1,1,1,'','',0)
	
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0408','157','选择单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0408','158','选择折扣',1,1,1,1,'','',0)
	
	--POS销售流水查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('04091703','005','打印',1,1,1,1,'','',0)
	--POS收银流水查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('04091704','005','打印',1,1,1,1,'','',0)
	
	--零售销售统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0404','005','打印',1,1,1,1,'','',0)
	--制单人收款统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0406','005','打印',1,1,1,1,'','',0)
	--零售日销售统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0407','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0407','011','成本查看',1,1,1,1,'','',0)
	--零售时段分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('04091706','005','打印',1,1,1,1,'','',0)
	--同价调拨单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0501','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0501','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0501','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0501','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0501','067','存为草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0501','137','捡货',1,1,1,1,'','',0)
	--变价调拨单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0502','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0502','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0502','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0502','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0502','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0502','067','存为草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0502','137','捡货',1,1,1,1,'','',0)
	--明细调整单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0503','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0503','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0503','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0503','067','存为草稿',1,1,1,1,'','',0)
	--报溢单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0504','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0504','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0504','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0504','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0504','067','存为草稿',1,1,1,1,'','',0)
	--报损单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0505','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0505','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0505','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0505','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0505','067','存为草稿',1,1,1,1,'','',0)
	
	--其它出库单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0513','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0513','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0513','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0513','008','科目详情',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0513','009','修改单价',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0513','010','修改折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0513','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0513','067','存为草稿',1,1,1,1,'','',0)
        INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0513','137','捡货',1,1,1,1,'','',0)
	
	
	--其它入库单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0514','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0514','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0514','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0514','008','科目详情',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0514','009','修改单价',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0514','010','修改折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0514','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0514','067','存为草稿',1,1,1,1,'','',0)
        INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0514','137','捡货',1,1,1,1,'','',0)
	
	--拆卸组装单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0506','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0506','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0506','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0506','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0506','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0506','067','存为草稿',1,1,1,1,'','',0)
	--获赠单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0507','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0507','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0507','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0507','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0507','067','存为草稿',1,1,1,1,'','',0)
	--赠送单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0508','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0508','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0508','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0508','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0508','067','存为草稿',1,1,1,1,'','',0)
	--成本调整单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0509','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0509','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0509','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0509','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0509','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0509','067','存为草稿',1,1,1,1,'','',0)
	--库存状况表
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051001','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051001','011','成本查看',1,1,1,1,'','',0)

	--'051010','库龄分析'
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051010','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051010','011','成本查看',1,1,1,1,'','',0)

    --其它出入库统计
    INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051011','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051011','011','成本查看',1,1,1,1,'','',0)
	--全能进销存变动表
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051002','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051002','011','成本查看',1,1,1,1,'','',0)
	--商品库存分布
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051003','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051003','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051003','099','查看所有仓库分布',1,1,1,1,'','',0)
	--商品出入库分布
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051004','005','打印',1,1,1,1,'','',0)
	--可用库存查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051005','005','打印',1,1,1,1,'','',0)
	--停用商品查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051006','005','打印',1,1,1,1,'','',0)
	--积压商品查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051007','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051007','011','成本查看',1,1,1,1,'','',0)
	--唯一码查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051008','005','打印',1,1,1,1,'','',0)

	--库存周转率分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051009','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051009','011','成本查看',1,1,1,1,'','',0)
	--商品上下限报警设置
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051101','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051101','040','设置',1,1,1,1,'','',0)
	--库存上限报警
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051102','005','打印',1,1,1,1,'','',0)
	--库存下限报警
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051103','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051103','044','生成订单',1,1,0,1,'','',0)
	--商品断码报警
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051104','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051104','043','生成草稿',1,1,0,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051104','044','生成订单',1,1,0,1,'','',0)
	--盘点准备
	--盘点准备
	--盘点单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051202','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051202','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051202','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051202','013','保存',1,1,1,1,'','',0)
	--盘点准备查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051206','005','打印',1,1,1,1,'','',0)
	--自动盘盈盘亏
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051203','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051203','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051203','032','盘点处理',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051203','074','修改他人盘点单',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051203','075','删除他人盘点单',1,1,1,1,'','',0)
	--历史盘点查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051204','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('051204','011','成本查看',1,1,1,1,'','',0)
	--盘点机接口
	--配货申请单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0601','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0601','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0601','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0601','081','保存订单',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0601','125','配货',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0601','126','退货',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0601','127','调配',1,1,1,1,'','',0)
	--同价配货单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0602','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0602','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0602','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0602','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0602','064','修改验收数量',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0602','067','存为草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0602','125','配货',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0602','126','退货',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0602','127','调配',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0602','137','捡货',1,1,1,1,'','',0)
	--变价配货单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0603','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0603','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0603','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0603','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0603','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0603','064','修改验收数量',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0603','067','存为草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0603','125','配货',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0603','126','退货',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0603','127','调配',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0603','137','捡货',1,1,1,1,'','',0)

	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0603','157','选择单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0603','009','修改单价',1,1,1,1,'','',0)

	--加盟商配货订单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0604','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0604','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0604','009','修改单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0604','010','修改折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0604','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0604','081','保存订单',1,1,1,1,'','',0)
	
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0604','157','选择单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0604','158','选择折扣',1,1,1,1,'','',0)
	
	--加盟商退货申请单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0605','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0605','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0605','009','修改单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0605','010','修改折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0605','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0605','081','保存订单',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0605','157','选择单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('060','158','选择折扣',1,1,1,1,'','',0)
	--加盟商配货单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0606','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0606','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0606','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0606','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0606','009','修改单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0606','157','选择单价',1,1,1,1,'','',0)
	
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0606','010','修改折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0606','158','选择折扣',1,1,1,1,'','',0)
	
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0606','067','存为草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0606','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0606','137','捡货',1,1,1,1,'','',0)
	--加盟商退货单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0607','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0607','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0607','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0607','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0607','009','修改单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0607','010','修改折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0607','157','选择单价',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0607','158','选择折扣',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0607','067','存为草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0607','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0607','137','捡货',1,1,1,1,'','',0)
	--配货验收
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0608','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0608','021','复制草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0608','025','红冲',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0608','057','验收',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0608','079','红冲他人单据',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0608','137','捡货',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('0608','161','差额调整单成本查看',1,1,0,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('0608','162','加盟配货验收单成本查看',1,1,1,1,'','',1)

    INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('0699','005','打印',1,1,1,1,'','',1)
    INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('0699','168','生成配货订单',1,1,1,1,'','',1)

	--内部配货统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('060901','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('060901','011','成本查看',1,1,1,1,'','',0)
	--加盟商配货分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('060902','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('060902','011','成本查看',1,1,1,1,'','',0)
	--配货单汇总分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('060903','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('060903','011','成本查看',1,1,1,1,'','',0)

	--收款单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0701','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0701','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0701','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0701','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0701','067','存为草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0701','128','销售收款',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0701','129','预收账款',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0701','130','其他收款',1,1,1,1,'','',0)
	--付款单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0702','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0702','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0702','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0702','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0702','067','存为草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0702','131','采购付款',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0702','132','预付账款',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0702','133','其他付款',1,1,1,1,'','',0)

	--往来核销
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0710','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0710','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0710','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0710','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0710','067','存为草稿',1,1,1,1,'','',0)


	--应收款增加
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0703','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0703','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0703','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0703','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0703','067','存为草稿',1,1,1,1,'','',0)
	--应收款减少
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0704','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0704','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0704','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0704','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0704','067','存为草稿',1,1,1,1,'','',0)
	--应付款增加
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0705','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0705','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0705','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0705','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0705','067','存为草稿',1,1,1,1,'','',0)
	--应付款减少
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0706','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0706','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0706','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0706','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0706','067','存为草稿',1,1,1,1,'','',0)
	--代销结算调整
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0707','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0707','013','保存',1,1,1,1,'','',0)
	--退换货调整
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0709','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0709','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0709','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0709','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0709','042','审核',1,1,1,1,'','',0)

	--应收款查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('070801','005','打印',1,1,1,1,'','',0)
	--应付款查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('070802','005','打印',1,1,1,1,'','',0)

	--代销对账
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('070806','005','打印',1,1,1,1,'','',0)
	
	--超期应收款
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('070807','005','打印',1,1,1,1,'','',0)

	--往来分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('070803','005','打印',1,1,1,1,'','',0)
	--账龄分析
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('070804','005','打印',1,1,1,1,'','',0)
	--按单结算查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('070805','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('070805','011','成本查看',1,1,0,1,'','',0)


	--070808','内部往来查询'
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('070808','005','打印',1,1,1,1,'','',0)

	--会计凭证
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0801','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0801','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0801','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0801','067','存为草稿',1,1,1,1,'','',0)
	--现金费用单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0802','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0802','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0802','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0802','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0802','067','存为草稿',1,1,1,1,'','',0)
	
	--固定资产折旧
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0813','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0813','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0813','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0813','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0813','067','存为草稿',1,1,1,1,'','',0)
	
	--固定资产购置
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0814','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0814','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0814','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0814','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0814','067','存为草稿',1,1,1,1,'','',0)
	
	--固定资产变卖
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0815','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0815','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0815','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0815','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0815','067','存为草稿',1,1,1,1,'','',0)
	
	--固定资产查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0816','005','打印',1,1,1,1,'','',0)
	
	--一般费用单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0803','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0803','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0803','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0803','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0803','067','存为草稿',1,1,1,1,'','',0)
	--其它收入单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0804','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0804','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0804','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0804','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0804','067','存为草稿',1,1,1,1,'','',0)
	--内部转款单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0805','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0805','006','录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0805','007','过账',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0805','008','科目详情',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0805','067','存为草稿',1,1,1,1,'','',0)
	--现金银行查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0806','005','打印',1,1,1,1,'','',0)
	--费用支出
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('080701','005','打印',1,1,1,1,'','',0)
	--机构费用统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('080702','005','打印',1,1,1,1,'','',0)
	--部门费用统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('080703','005','打印',1,1,1,1,'','',0)
	--其他收入查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0808','005','打印',1,1,1,1,'','',0)
	--职员创利报表
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0809','005','打印',1,1,1,1,'','',0)
	--损益表
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0810','005','打印',1,1,1,1,'','',0)
	--资产负债表
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0811','005','打印',1,1,1,1,'','',0)
	--凭证接口
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0812','005','打印',1,1,1,1,'','',0)
	--业务草稿
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0901','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0901','016','单据转换',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0901','021','复制草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0901','038','删除草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0901','056','修改他人草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0901','078','删除他人草稿  ',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0901','145','查看他人草稿',1,1,1,1,'','',0)

	--经营历程
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0902','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0902','021','复制草稿',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0902','025','红冲',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0902','050','修改附加说明',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0902','079','红冲他人单据',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0902','080','修改他人单据附加说明',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0902','088','修改摘要',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0902','089','修改他人单据摘要',1,1,1,1,'','',0)
	--单据审核
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0903','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0903','020','反审核',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0903','021','复制草稿',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0903','038','删除',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0903','039','删除审核完成的单据',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0903','042','审核',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0903','102','审核历史',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0903','103','原始单据',1,1,1,1,'','',0)

	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0904','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0904','102','审核历史',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0904','103','原始单据',1,1,1,1,'','',0)

	--订单查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0905','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0905','019','订单转换',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0905','035','强制完成',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0905','071','修改他人订单',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0905','072','删除他人订单',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0905','098','订单复制',1,1,1,1,'','',0)

	--商品订货统计
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0906','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0906','011','成本查看',1,1,1,1,'','',0)
	--单位订货统计
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0907','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('0907','011','成本查看',1,1,1,1,'','',0)
	
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('061001','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('061002','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('061002','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('061003','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('061003','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('061004','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030901','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('030902','005','打印',1,1,1,1,'','',0)
	--商品采购订货统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('020701','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('020701','011','成本查看',1,1,1,1,'','',0)
	--供应商采购订货统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('020702','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('020702','011','成本查看',1,1,1,1,'','',0)
-- 	--采购订单明细分析
-- 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('020703','005','打印',1,1,1,1,'','',0)
-- 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('020703','011','成本查看',1,1,1,1,'','',0)
-- 	--采购订单汇总分析
-- 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('020704','005','打印',1,1,1,1,'','',0)
-- 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('020704','011','成本查看',1,1,1,1,'','',0)
	

	--采购明细分析
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021103','005','打印',1,1,1,1,'','',0)
 	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021103','011','成本查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021103','103','原始单据',1,1,1,1,'','',0)


	--采购建议表
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('021111','005','打印',1,1,1,1,'','',0)


	--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('061001','加盟商商品订货统计','061001',1,1,0,234,1)
	--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('061002','内部商品申请统计','061002',1,1,0,235,0)
	--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0309','商品销售订货统计','0309',1,1,0,232,1)
	--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0207','商品采购订货统计','0207',1,1,0,231,0)
	
	--采购入库单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090801','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090801','011','成本查看',1,1,1,1,'','',0)

	--采购退货单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090802','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090802','011','成本查看',1,1,1,1,'','',0)
	--销售出库单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090803','005','打印',1,1,1,1,'','',0)
	--销售退货单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090804','005','打印',1,1,1,1,'','',0)
	--销售换货单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090805','005','打印',1,1,1,1,'','',0)
	--零售单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090806','005','打印',1,1,1,1,'','',0)
	--同价调拨单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090807','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090807','011','成本查看',1,1,1,1,'','',0)
	--变价调拨单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090808','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090808','011','成本查看',1,1,1,1,'','',0)
	--明细调整单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090809','005','打印',1,1,1,1,'','',0)
	--报溢单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090810','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090810','011','成本查看',1,1,1,1,'','',0)
	--报损单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090811','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090811','011','成本查看',1,1,1,1,'','',0)
	--拆卸组装单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090812','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090812','011','成本查看',1,1,1,1,'','',0)
	--获赠单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090813','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090813','011','成本查看',1,1,1,1,'','',0)
	--赠送单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090814','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090814','011','成本查看',1,1,1,1,'','',0)
	--成本调整单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090815','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090815','011','成本查看',1,1,1,1,'','',0)
	--同价配货单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090816','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090816','011','成本查看',1,1,1,1,'','',0)
	--变价配货单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090817','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090817','011','成本查看',1,1,1,1,'','',0)
	--加盟商配货单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090818','005','打印',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090818','011','成本查看',1,1,1,1,'','',0)
	--加盟商退货单
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090819','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('090819','011','成本查看',1,1,1,1,'','',0)
	--VIP卡类型设置
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1001','001','新增',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1001','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1001','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1001','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1001','034','启用',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1001','045','停用',1,1,1,1,'','',0)
	--VIP制卡管理
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1002','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1002','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1002','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1002','017','单一制卡',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1002','033','批量制卡',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1002','034','启用',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1002','045','停用',1,1,1,1,'','',0)
	--VIP发卡
	--VIP卡管理
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','023','挂失',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','106','积分转储值',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','006','写入IC卡',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','167','导出Excel',1,1,1,1,'','',0)

	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','152','启用',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','153','VIP卡导入',1,1,0,1,'','',0)

	
	--VIP卡管理新增按钮
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','045','停用',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','105','作废',1,1,1,1,'','',0)

	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','026','恢复',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','124','修改积分',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','027','积分修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','091','修改VIP密码',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1004','123','清空VIP密码',1,1,1,1,'','',0)
	--VIP充值
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1005','087','允许负数充值',1,1,1,1,'','',0)
	--积分处理
	--VIP积分处理查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('100701','005','打印',1,1,1,1,'','',0)
	--VIP积分修改查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('100702','005','打印',1,1,1,1,'','',0)
	--VIP客户消费统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('100703','005','打印',1,1,1,1,'','',0)
	--VIP客户商品消费统计
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('100704','005','打印',1,1,1,1,'','',0)
	--VIP会员生日查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('100705','005','打印',1,1,1,1,'','',0)
	--VIP储值查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('100706','005','打印',1,1,1,1,'','',0)
	--商品价格管理
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('100801','003','修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('100801','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('100801','011','最近进价查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('100801','047','物价生成',1,1,1,1,'','',0)
	--价格折扣跟踪
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('100802','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('100802','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('100802','011','成本查看',1,1,1,1,'','',0)
	--物价信息查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('100803','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('100803','011','成本查看',1,1,1,1,'','',0)
	--系统配置
	--单据格式配置
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('110201','048','显示',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('110201','049','修改单据编号前缀',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('110201','055','修改列名',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('110201','100','选择自定义列',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('110201','101','记忆上行信息',1,1,1,1,'','',0)
	--多条码设置
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1112','013','编辑',1,1,1,1,'','',0)

	--单据编号格式配置
	--单据库存查询配置
	--单据自定义列配置
	--权限管理(去掉新新，删除权限，只有超级用户才有）
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1105','001','新增',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1105','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1105','012','绑定安全钥匙',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1105','037','取消安全钥匙',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1105','041','设置权限',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1105','148','设置IP',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1105','149','清除IP',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1105','150','限制登录',1,1,1,1,'','',0)

	--月结存
	--年结存
	--系统重建
	--启用报警
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1107','138','库存上下限报警',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1107','139','应收应付上限报警',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1107','140','订单报警',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1107','141','超期应收款报警',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1107','142','断码报警',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1107','143','会员生日报警',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1107','005','打印',1,1,1,1,'','',0)
	--月结存信息表
	--操作日志管理
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1110','004','删除',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1110','005','打印',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('1110','086','清理',1,1,1,1,'','',0)
	--全局权限
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('13','015','查看他人过账单据',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('13','022','往来单位金额查看',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('13','065','单据条码打印权限',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('13','077','单据中查看往来销售状况表',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('13','083','商品库存详情的成本查看',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('13','084','POS零售单价格修改',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('13','085','单据中查看VIP信息',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('13','090','操作员键盘录入VIP卡号',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('13','097','导出到EXCEL',1,1,1,1,'','',0)
	--POS结存
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('13','154','会员卡支持键盘录入',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid) VALUES ('13','156','单据刷价',1,1,1,1,'','',0)


	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040904','112','结存过账',1,1,1,1,'','',0)
	--POS盘点单查询
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('04091705','113','生成盘点单',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('04091705','114','批量生成',1,1,1,1,'','',0)
	INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('04091705','005','打印',1,1,1,1,'','',0)
	
	--POS登记
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040901','001','新增',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040901','003','修改',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040901','004','删除',1,1,1,1,'','',0)
	--INSERT INTO actionList(moduleid,actionid,actionname,zydflag,zgflag,jmdflag,plusverflag,expandid,remark,orderid)	VALUES ('040901','115','修改密码',1,1,1,1,'','',0)
	
	
	-- 最大值  144




END
GO


--  ********************************************************************************************  webmenu--  *****************************************
DELETE FROM WebMENU

/*
基本信息	商品管理	商品信息
		颜色
		颜色组
		尺码
		尺码组
		辅助属性类型
		辅助属性
		条码对照表
		条码打印
	往来单位	供应商
		客户
		代销单位
	分支机构	
	存货仓库	
	财务信息	现金银行
		会计科目
	职员	
	部门	
	期初建账	库存期初
		应收期初
		应付期初
		现金银行期初
		账务期初
		
	期初资产负债表	
	加盟商基本信息	存货仓库
		客户
		职员
		部门
		现金银行
		会计科目
	启用账套	
*/

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('01','基础信息','01',1,1,0,1,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0101','商品管理','0101',1,1,0,2,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010101','商品信息','010101',1,1,0,3,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010102','颜色','010102',1,1,0,4,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010103','颜色组','010103',1,1,0,5,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010104','尺码','010104',1,1,0,6,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010105','尺码组','010105',1,1,0,7,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010110','配码','0101051',1,1,0,268,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010106','辅助属性类型','010106',1,1,0,8,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010107','辅助属性','010107',1,1,0,9,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010108','条码对照表','010108',1,1,0,10,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010109','条码打印','010111',1,1,0,11,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010111','条码方案','010109',1,1,0,353,0)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0102','往来单位','0102',1,1,0,12,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010201','供应商','010201',1,1,0,13,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010202','客户','010202',1,1,0,14,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010203','代销单位','010203',1,1,0,15,0)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0103','分支机构','0103',1,1,0,16,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0104','存货仓库','0104',1,1,0,17,0)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0105','财务信息','0105',1,1,0,18,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010501','现金银行','010501',1,0,0,19,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010502','会计科目','010502',1,1,0,20,0)


INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0106','职员','0106',1,1,0,21,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0107','部门','0107',1,1,0,22,0)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0112','业务信息','01071',1,1,0,257,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('011201','发货类型','010711',1,1,0,258,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('011202','收货类型','010712',1,1,0,259,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('011203','退货类型','010713',1,1,0,260,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('011204','出库类型','010714',1,1,0,261,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('011205','入库类型','010715',1,1,0,262,0)


INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0108','期初建账','0108',1,1,0,23,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010801','库存期初','010801',1,1,0,24,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010802','应收期初','010802',1,1,0,25,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010803','应付期初','010803',1,1,0,26,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010804','现金银行期初','010804',1,1,0,27,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('010805','账务期初','010805',1,1,0,28,1)


INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0109','期初资产负债表','0109',1,1,0,29,1)


INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0110','加盟商基本信息','0110',1,1,0,30,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('011001','存货仓库','011001',1,1,0,31,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('011002','客户','011002',1,1,0,32,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('011003','职员','011003',1,1,0,33,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('011004','部门','011004',1,1,0,34,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('011007','业务信息','0110041',1,1,0,263,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('01100701','发货类型','01100411',1,1,0,264,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('01100702','退货类型','01100412',1,1,0,265,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('01100703','出库类型','01100413',1,1,0,266,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('01100704','入库类型','01100414',1,1,0,267,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('011005','现金银行','011005',1,0,0,35,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('011006','会计科目','011006',1,1,0,36,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0111','启用账套','0111',1,1,0,37,1)

/*
采购管理	采购订单	
	采购入库单	
	采购退货单	
	采购订货统计
		商品采购订货统计
		供应商采购订货统计
	商品采购统计		
	采购汇总分析
	供应商供货统计	
	商品采购分析	
	采购建议表
*/

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('02','采购管理','02',1,1,0,38,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0201','采购订单','0201',1,1,7,39,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0202','采购入库单','0202',1,1,34,40,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0203','采购退货单','0203',1,1,6,41,0)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0211','采购报表','020301',1,1,0,335,0)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('021101','采购订单明细分析','021101',1,1,0,336,0)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('021102','采购订单汇总分析','021102',1,1,0,337,0)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('021107','商品采购统计','020302',1,1,0,42,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('021109','供应商供货统计','020304',1,1,0,43,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('021110','商品采购分析','020305',1,1,0,44,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('021111','采购建议表','020306',1,1,0,251,0)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('021103','采购明细分析','020307',1,1,0,338,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('021112','采购汇总分析','020308',1,1,0,312,0)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('021104','供应商供货准时分析','020309',1,1,0,342,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('021105','供应商供货对照表','020310',1,1,0,349,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('021106','机构采购分布汇总统计','020311',1,1,0,363,0)



INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0207','采购订货统计','020301',1,1,0,276,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('020701','商品采购订货统计','020701',1,1,0,231,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('020702','供应商采购订货统计','020702',1,1,0,277,0)



--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0209','采购汇总分析','020401',1,1,0,312,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0210','采购业务配置','0209',1,1,0,319,0)












/*
销售管理	销售订单	
	销售出库单	
	销售退货单	
	销售换货单	
	订货统计
		商品销售订货统计
		客户订货统计
		
	业务统计	职员业务统计
		客户业务统计

	销售报表	
		商品销售明细表
		销售状况表
		商品销售分析
		客户销售分析
		仓库销售分布		
		销售年月日统计
		商品动销比分析报表
		单品分析
		--畅滞销分析
		客户退换货查询
		
	销售排行榜	
		商品销售排行榜
		客户销售排行榜
		仓库销售排行榜
		职员销售排行榜
		颜色销售排行榜
		尺码销售排行榜
		商品颜色尺码销售排行榜
	进销存统计表	
		商品进销存统计
		仓库进销存统计
*/



INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('03','销售管理','03',1,1,0,45,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0301','销售订单','0301',1,1,8,46,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0302','销售出库单','0302',1,1,11,47,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0303','销售退货单','0303',1,1,45,48,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0304','销售换货单','0304',1,1,24,49,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0309','订货统计','030401',1,1,0,278,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030901','商品销售订货统计','030901',1,1,0,232,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030902','客户订货统计','030902',1,1,0,279,1)

--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0305','客户业务统计','0305',1,1,0,52,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030501','职员业务统计','030501',1,1,0,51,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030502','客户业务统计','030502',1,1,0,52,1)


INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0306','销售报表','0306',1,1,0,53,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030601','商品销售明细表','030601',1,1,0,54,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030602','销售状况表','030602',1,1,0,55,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030603','商品销售分析','030603',1,1,0,56,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030604','客户销售分析','030604',1,1,0,57,1)

--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030606','客户退换货分析','030606',1,1,0,1,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030606','销售年月日统计','030606',1,1,0,59,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030610','商品动销比分析报表','03060601',1,1,0,282,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030611','商品售罄率分析','03060602',1,1,0,309,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030612','客户上货情况分析表','03060603',1,1,0,311,0)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030613','销售订单明细分析','03060604',1,1,0,327,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030614','销售订单汇总分析','03060605',1,1,0,334,0)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030607','单品分析','030607',1,1,0,60,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030608','畅滞销分析','030608',1,1,0,61,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030609','客户退换货查询','030609',1,1,0,275,0)

--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030616','发货类型销售分析','030616',1,1,0,343,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030618','销售明细分析','030618',1,1,0,351,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030619','销售汇总分析','030619',1,1,0,352,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030620','销售综合分析','030620',1,1,0,357,1) 换到综合分析下面

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030621','销售成本分析','030621',1,1,0,374,1)


--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0307','销售排行榜','0307',1,1,0,62,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030701','商品销售排行榜','030701',1,1,0,63,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030702','客户销售排行榜','030702',1,1,0,64,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030703','仓库销售排行榜','030703',1,1,0,65,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030704','职员销售排行榜','030704',1,1,0,66,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030705','颜色销售排行榜','030705',1,1,0,67,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030706','尺码销售排行榜','030706',1,1,0,68,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030707','商品颜色尺码销售排行榜','030707',1,1,0,69,1)


--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0308','进销存统计表','0308',1,1,0,70,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030801','商品进销存统计','030801',1,1,0,71,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('030802','仓库进销存统计','030802',1,1,0,72,1)

--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0310','经营报表','0308',1,1,0,250,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0312','销售业务配置','0312',1,1,0,320,1)

/*
零售管理	零售单	
	零售收银设置	
	零售单配置	
	零售销售统计	
	零售收银报表	
	制单人收款统计	
	零售日销售统计		
*/		
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('04','零售管理','04',1,1,0,73,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0401','零售单','0401',1,1,12,74,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0408','代销零售单','0401',1,1,100,227,0)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0402','零售收银设置','0402',1,1,0,75,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0403','零售单配置','0403',1,1,0,76,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0404','零售销售统计','0404',1,1,0,77,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0405','零售收银报表','0405',1,1,0,78,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0406','制单人收款统计','0406',1,1,0,79,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0407','零售日销售统计','0407',1,1,0,80,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0413','价格变迁零售统计','040701',1,1,0,344,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0410','零售分析','040702',1,1,0,305,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('041003','商品零售综合分析','04070203',1,1,0,315,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('041004','商店商品售罄率分析','04070204',1,1,0,316,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('041005','商店零售分析','04070205',1,1,0,317,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('041006','商店sku动销比分析','04070206',1,1,0,318,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('041007','零售对比分析','04070207',1,1,0,341,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('041009','商品零售分析','04070209',1,1,0,347,1)

--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('041010','促销赠品分析','04070210',1,1,0,377,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('041011','POS销存动态跟踪','04070211',1,1,0,378,0)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('041012','机构促销分析','04070212',1,1,0,379,1)




INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0409','POS管理','0410',1,1,0,236,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('040901','POS登记','040901',1,1,0,237,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('040902','POS收银设置','040902',1,1,0,238,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('040903','促销管理','040903',1,1,0,239,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('040916','POS收银方式设置','040916',1,1,0,393,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('040915','POS人员管理','040915',1,1,0,394,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('040911','店铺分组管理','040911',1,1,0,395,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('040912','POS盘点指令单','040912',1,1,0,396,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('040913','特定商品设置','040913',1,1,0,397,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('040914','营业员商品权限范围','040914',1,1,0,398,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('040917','POS报表','040918',1,1,0,399,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('040904','POS结存','040917',1,1,0,245,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('04091701','促销赠品分析','04091701',1,1,0,377,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('04091702','机构促销分析','04091702',1,1,0,379,1)

--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('04090301','特价促销','04090301',1,1,0,240,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('04090302','赠品促销','04090302',1,1,0,241,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('04090303','手工促销','04090303',1,1,0,242,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('04090304','组合促销','04090304',1,1,0,243,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('04090305','促销方案管理','04090305',1,1,0,244,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('04091703','POS销售流水查询','04091703',1,1,0,246,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('04091704','POS收银流水查询','04091704',1,1,0,247,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('04091705','POS盘点单查询','04091705',1,1,0,248,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('04091706','零售时段分析','04091706',1,1,0,314,0)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0412','零售计划管理','0409',1,1,0,298,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('041201','零售计划配置','041201',1,1,0,299,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('041202','零售计划单','041202',1,1,0,300,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('041203','零售计划单查询','041203',1,1,0,301,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('041204','零售计划完成统计','041204',1,1,0,302,1)
 
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0411','零售业务配置','0411',1,1,0,321,1)
	
/*
库存管理	同价调拨单	
	变价调拨单	
	明细调整单	
	报溢单	
	报损单	
	拆卸组装单	
	获赠单	
	赠送单	
	成本调整单	
	库存报表	库存状况表
		全能进销存变动表
		商品库存分布
		商品出入库分布
		可用库存查询
		停用商品查询
		积压商品查询
	库存报警	商品上下限报警设置
		库存上限报警
		库存下限报警
		商品断码报警
	盘点管理	盘点准备
		盘点单
		自动盘盈盘亏
		历史盘点查询
		盘点机接口
*/

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('05','库存管理','05',1,1,0,81,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0501','同价调拨单','0501',1,1,17,82,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0502','变价调拨单','0502',1,1,21,83,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0503','明细调整单','0503',1,1,150,84,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0504','报溢单','0504',1,1,14,85,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0505','报损单','0505',1,1,9,86,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0513','其它出库单','050901',1,1,251,272,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0514','其它入库单','050902',1,1,252,273,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0506','拆卸组装单','0506',1,1,16,87,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0507','获赠单','0507',1,1,126,88,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0508','赠送单','0508',1,1,139,89,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0509','成本调整单','0509',1,1,57,90,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0510','库存报表','0510',1,1,0,91,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051001','库存状况表','051001',1,1,0,92,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051002','全能进销存变动表','051002',1,1,0,93,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051003','商品库存分布','051003',1,1,0,94,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051004','商品出入库分布','051004',1,1,0,95,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051005','可用库存查询','051005',1,1,0,96,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051006','停用商品查询','051006',1,1,0,97,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051007','积压商品查询','051007',1,1,0,98,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051008','唯一码查询','051008',1,1,0,252,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051009','库存周转率分析','051009',1,1,0,313,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051010','库龄分析','051010',1,1,0,360,0)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051011','商品进销存分析','051011',1,1,0,361,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051011','其它出入库单统计','051011',1,1,0,454,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0511','库存报警','0511',1,1,0,99,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051101','商品上下限报警设置','051101',1,1,0,100,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051102','库存上限报警','051102',1,1,0,101,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051103','库存下限报警','051103',1,1,0,102,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051104','商品断码报警','051104',1,1,0,103,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0512','盘点管理','0512',1,1,0,104,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051201','盘点准备','051201',1,1,0,105,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051202','盘点单','051202',1,1,70,106,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051203','自动盘盈盘亏','051203',1,1,0,107,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051204','历史盘点查询','051204',1,1,0,108,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051206','盘点准备查询','051204',1,1,0,384,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('051205','盘点机接口','051205',1,1,0,109,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('05120501','导出库存商品到盘点机','05120501',1,1,0,228,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('05120502','导入盘点机数据','05120502',1,1,0,229,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0515','库存业务配置','0515',1,1,0,322,1)

/*
配送管理	配货申请单	
	同价配货单	
	变价配货单	
	加盟商配货订单	
	加盟商退货申请单	
	加盟商配货单	
	加盟商退货单	
	配货验收	
	订货统计
		内部商品申请统计
		内部机构申请统计
		加盟商商品订货统计
		加盟商订货统计
	配货报表	
		商品配货统计
		加盟商配货分析
*/
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('06','配送管理','06',1,1,0,110,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0601','配货申请单','0601',1,1,211,111,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0602','同价配货单','0602',1,1,218,112,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0603','变价配货单','0603',1,1,212,113,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0604','加盟商配货订单','0604',1,1,221,114,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0605','加盟商退货申请单','0605',1,1,223,115,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0606','加盟商配货单','0606',1,1,222,116,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0607','加盟商退货单','0607',1,1,234,117,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0608','配货验收','0608',1,1,0,118,1)
--只针对客户定制,用完注释
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0699','商店配货申请表','060801',1,1,0,99999,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0609','配货报表','0609',1,1,0,119,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('060901','内部配货统计','060901',1,1,0,120,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('060902','加盟商配货分析','060902',1,1,0,121,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('060903','配货单汇总分析','060903',1,1,0,328,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('060904','配货申请单明细分析','060904',1,1,0,329,0)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('060905','配货申请单汇总分析','060905',1,1,0,345,0)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0610','订货统计','0610',1,1,0,233,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('061002','内部商品申请统计','061001',1,1,0,235,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('061003','内部机构申请统计','0610012',1,1,0,280,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('061001','加盟商商品订货统计','0610013',1,1,0,234,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('061004','加盟商订货统计','0610014',1,1,0,281,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0611','智能配货','0611',1,1,0,253,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('061101','机构配货规则设置','061101',1,1,0,254,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('061102','按规则配货','061102',1,1,0,255,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('061103','按订单配货','061103',1,1,0,256,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0612','配送业务配置','0612',1,1,0,323,1)


/*
综合分析
	商品售罄率分析
	销售状况表
	客户上货情况分析表
*/
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('15','综合分析','0699',1,1,0,308,1)
/*
往来管理	收款单	
	付款单	
	往来核销
	应收款增加	
	应收款减少	
	应付款增加	
	应付款减少	
	代销结算调整	
	退换货调整
	往来报表	应收款查询
		应付款查询
		往来分析
		账龄分析
		按单结算查询
		代销对账
*/
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('07','往来管理','07',1,1,0,122,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0701','收款单','0701',1,1,4,123,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0702','付款单','0702',1,1,66,124,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0710','往来核销','070201',1,1,253,340,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0703','应收款增加','0703',1,1,116,125,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0704','应收款减少','0704',1,1,115,126,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0705','应付款增加','0705',1,1,128,127,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0706','应付款减少','0706',1,1,129,128,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0707','代销结算调整','0707',1,1,131,129,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0709','退换货调整','070701',1,1,0,274,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0708','往来报表','0708',1,1,0,130,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('070801','应收款查询','070801',1,1,0,131,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('070802','应付款查询','070802',1,1,0,132,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('070803','往来分析','070803',1,1,0,133,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('070804','应收款账龄分析','070804',1,1,0,134,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('070805','按单结算查询','070805',1,1,0,135,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('070806','代销对账','070806',1,1,0,136,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('070807','超期应收款','070807',1,1,0,230,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('070808','内部往来查询','070808',1,1,0,356,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0711','往来业务配置','0710',1,1,0,381,1)

/*
财务管理	会计凭证	
	现金费用单	
	一般费用单	
	其它收入单	
	内部转款单	
	现金银行查询	
	费用查询	费用支出			
		机构费用统计
		部门费用统计
	其他收入查询	
	职员创利报表	
	损益表	
	资产负债表	
	凭证接口	
*/
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('08','财务管理','08',1,1,0,137,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0801','会计凭证','0801',1,1,125,138,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0802','现金费用单','0802',1,1,35,139,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0803','一般费用单','0803',1,1,36,140,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0804','其它收入单','0804',1,1,93,141,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0805','内部转款单','0805',1,1,77,142,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0813','固定资产折旧','080502',1,1,78,269,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0814','固定资产购置','080501',1,1,84,270,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0815','固定资产变卖','080503',1,1,85,271,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0816','固定资产查询','080504',1,1,0,283,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0806','现金银行查询','0806',1,1,0,143,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0807','费用查询','0807',1,1,0,144,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('080701','费用支出','080701',1,1,0,145,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('080702','机构费用统计','080702',1,1,0,146,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('080703','部门费用统计','080703',1,1,0,147,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0808','其它收入查询',		'0808',1,1,0,148,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0809','职员创利报表','0809',1,1,0,149,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0810','损益表','0810',1,1,0,150,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0811','资产负债表','0811',1,1,0,151,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0812','凭证接口','0812',1,1,0,152,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0817','财务业务配置','0817',1,1,0,380,1)
/*
单据中心	业务草稿	
	经营历程	
	单据审核	
	审核查询	
	订单查询	
	商品订货统计		
	单位订货统计	
	单据统计	采购入库单
		采购退货单
		销售出库单
		销售退货单
		销售换货单
		零售单
		同价调拨单
		变价调拨单
		明细调整单
		报溢单
		报损单
		拆卸组装单
		获赠单
		赠送单
		成本调整单
		同价配货单
		变价配货单
		加盟商配货单
		加盟商退货单
*/
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('09','单据中心','09',1,1,0,153,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0901','业务草稿','0901',1,1,0,154,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0902','经营历程','0902',1,1,0,155,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0903','单据审核','0903',1,1,0,156,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0904','审核查询','0904',1,1,0,157,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0905','订单查询','0905',1,1,0,158,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0906','商品订货统计','0906',1,1,0,159,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0907','单位订货统计','0907',1,1,0,160,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0908','单据统计','0908',1,1,0,161,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090801','采购入库单','090801',1,1,0,162,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090802','采购退货单','090802',1,1,0,163,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090803','销售出库单','090803',1,1,0,164,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090804','销售退货单','090804',1,1,0,165,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090805','销售换货单','090805',1,1,0,166,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090806','零售单','090806',1,1,0,167,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090807','同价调拨单','090807',1,1,0,168,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090808','变价调拨单','090808',1,1,0,169,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090809','明细调整单','090809',1,1,0,170,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090810','报溢单','090810',1,1,0,171,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090811','报损单','090811',1,1,0,172,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090812','拆卸组装单','090812',1,1,0,173,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090813','获赠单','090813',1,1,0,174,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090814','赠送单','090814',1,1,0,175,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090815','成本调整单','090815',1,1,0,176,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090816','同价配货单','090816',1,1,0,177,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090817','变价配货单','090817',1,1,0,178,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090818','加盟商配货单','090818',1,1,0,179,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('090819','加盟商退货单','090819',1,1,0,180,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('0909','配货查询','0902',1,1,0,354,0)

/*
**商品进销存分析(全新）
供货商进销分析(暂时无文档）
**商品动销比分析(已有，调整位置）
**单品分析(已有，调整位置）
**销售综合分析(新增报表，销售状况表改名销售综合分析，原来的报表不动）
**销售排行榜(把原来的几种融合到一起)
**商品畅滞销分析(全新）
**销售年月日统计(已有，调整位置）
**客户业务统计(已有，调整位置）
**客户退换货查询，(已有，调整位置）
经营报表(已有，调整位置）
**赠品分析
**机构盈利统计分析
**销售收款统计
*/
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('16','综合分析','09',1,1,0,373,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1601','商品进销存分析','0901',1,1,0,364,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1602','供货商进销分析','0902',1,1,0,365,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1603','商品动销比分析','0903',1,1,0,282,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1604','单品分析','0904',1,1,0,60,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1607','商品畅滞销分析','0905',1,1,0,365,1)
-- INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1611','赠品分析','0906',1,1,0,366,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1605','销售综合分析','0907',1,1,0,367,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1609','客户业务统计','0908',1,1,0,52,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1610','客户退换货查询','0909',1,1,0,275,0)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1606','销售排行榜','0910',1,1,0,370,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1608','销售年月日统计','0911',1,1,0,59,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1613','销售收款统计','0912',1,1,0,371,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1614','销售经营报表','0913',1,1,0,250,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1615','机构盈利统计分析','0914',1,1,0,372,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1616','机构销售分布汇总统计','1616',1,1,0,58,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1617','机构收款统计','1617',1,1,0,383,1)







/*
辅助业务	VIP卡类型设置	
	VIP制卡管理	
	VIP发卡	
	VIP发卡管理	
	VIP充值	
	积分处理	
	VIP查询	VIP积分处理查询
		VIP积分修改查询
		VIP消费统计
		VIP商品消费统计
		VIP会员生日查询
		VIP储值查询
	物价管理	商品价格管理
		价格折扣跟踪
		物价信息查询
*/
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('10','辅助业务','10',1,1,0,181,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1001','VIP卡类型设置','1001',1,1,0,182,1)
-- 这个菜单删除了
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1002','VIP制卡管理','1002',1,1,0,183,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1003','VIP发卡','1003',1,1,0,184,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1009','VIP批量发卡','1003',1,1,0,249,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1004','VIP卡管理','1004',1,1,0,185,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1005','VIP充值','1005',1,1,0,186,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1006','积分处理','1006',1,1,0,187,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1007','VIP查询','1007',1,1,0,188,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('100701','VIP积分处理查询','100701',1,1,0,189,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('100702','VIP积分修改查询','100702',1,1,0,190,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('100703','VIP消费统计','100703',1,1,0,191,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('100704','VIP商品消费统计','100704',1,1,0,192,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('100705','VIP会员生日查询','100705',1,1,0,193,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('100706','VIP储值查询','100706',1,1,0,194,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1008','物价管理','1008',1,1,0,195,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('100801','商品价格管理','100801',1,1,0,196,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('100802','价格折扣跟踪','100802',1,1,0,197,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('100803','物价信息查询','100803',1,1,0,198,0)
/*
系统管理	系统配置	
	单据设置	单据格式配置
		单据编号格式配置
		单据库存查询配置
		单据自定义列配置
	价格设置	
	审核设置	
	权限管理	
	账套管理	月结存
		年结存
		系统重建
	启用报警	
	更换账套	
	月结存信息表
	数据搬移
		商品信息
		往来单位信息
			供应商
			客户
			代销单位
		仓库信息
		员工信息
	多账套查询
		方案管理
		基础信息
	操作日志管理	
	修改密码	
	版本信息
*/
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('11','系统管理','11',1,1,0,199,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1101','系统配置','1101',1,1,0,200,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1102','单据设置','1102',1,1,0,201,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('110201','单据格式配置','110201',1,1,0,202,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('110202','单据编号格式配置','110202',1,1,0,203,0)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('110203','单据库存查询配置','110203',1,1,0,204,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('110204','单据自定义列配置','110204',1,1,0,205,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('110205','单据打印次数配置','110205',1,1,0,325,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1103','价格设置','1103',1,1,0,206,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1104','审核设置','1104',1,1,0,207,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1105','权限管理','1105',1,1,0,208,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1106','账套管理','1106',1,1,0,209,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('110601','月结存','110601',1,1,0,210,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('110602','年结存','110602',1,1,0,211,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('110603','系统重建','110603',1,1,0,212,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1107','自动报警','1107',0,1,0,213,0)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1108','更换账套','1108',1,1,0,214,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1109','月结存信息表','1109',1,1,0,215,0)


 INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1114','数据搬移','110901',1,1,0,284,0)
 INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('111401','商品信息','11090101',1,1,0,285,0)
 INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('111402','往来单位信息','11090102',1,1,0,286,0)
 INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('11140201','供应商','1109010201',1,1,0,289,0)
 INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('11140202','客户','1109010202',1,1,0,290,0)
 INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('11140203','代销单位','1109010203',1,1,0,291,0)
 INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('11140204','加盟商客户','1109010204',1,1,0,292,0)
 INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('111403','仓库信息','11090103',1,1,0,287,0)
 INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('111404','员工信息','11090104',1,1,0,288,0)
 INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('111405','加盟员工信息','11090105',1,1,0,293,0)
 INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('111406','机构信息','11090100',1,1,0,324,0)

-- INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1115','多账套查询','110902',1,1,0,294,0)
-- INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('111501','系统管理','11090201',1,1,0,295,0)
-- INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('11150101','操作员管理','1109020101',1,1,0,296,0)
-- INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('11150102','方案管理','1109020102',1,1,0,297,0)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1110','操作日志管理','1110',1,1,0,216,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1111','修改密码','1111',1,0,0,217,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1112','多条码设置','1101',1,1,0,218,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1113','版本信息','1113',1,1,0,226,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1116','帮助文档','1113',1,0,0,326,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1117','本机信息','1117',1,1,1,358,1)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1118','短信配置','1118',1,1,0,375,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1119','发送短信','1119',1,1,0,376,1)
/*
帮助	在线帮助	
	版本信息	
*/

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('12','价格权限','12',0,1,0,219,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1201','售价权限','1201',0,1,0,220,1)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1202','进价权限','1202',0,1,0,221,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1203','抽成率权限','1203',0,1,0,222,0)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('13','全局权限','13',0,1,0,223,1)

/*
店账通
*/
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('15','店账通','10',1,1,0,385,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1501','账号管理','1001',1,1,0,386,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1502','初始化设置','1002',1,1,0,387,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1503','店账通使用','1003',1,1,0,388,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1504','登录店账通','1004',1,1,0,389,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1505','关于店账通','1005',1,1,0,390,0)

INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('17','订货会管理','1017',1,1,0,452,0)
INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1701','订货会','101701',1,1,0,453,0)

--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('14','帮助','14',1,1,0,224,0)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1401','在线帮助','1401',1,1,0,225,0)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1402','版本信息','1402',1,1,0,226,0)

/*
跨帐套查询  
   方案管理
   商品销售分析
   机构销售分析 
*/
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('14','跨帐套查询','1001',1,1,0,330,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1401','方案管理','1401',1,1,0,331,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1402','商品销售分析','1402',1,1,0,332,1)
--INSERT INTO WebMenu(ModuleID,ModuleName,ModuleOrder,ismenu,ispower,vchtype,offset,ifjm) VALUES ('1403','机构销售分析','1403',1,1,0,333,1)


--------------------------------------------------------------------------------------------------------------目前最大权限 offset 是 454 来自于 其他出入库统计
--------------------------------------------------------------------------------------------------------------非通用菜单 offset 是 99999 来自于 商店配货申请   moduleid  '0699'
--因为存在改权限问题，以下moduleid 不可再用 '030610','030607','030606','0305','030609','0310','0204','0209','0205','0206','0208'

/*
update EmployeePower SET moduleid ='1603'  where moduleid ='030610'
--单品分析
update EmployeePower SET moduleid ='1604'  where moduleid ='030607'
--销售年月日统计
update EmployeePower SET moduleid ='1608'  where moduleid ='030606'
--客户业务统计
update EmployeePower SET moduleid ='1609'  where moduleid ='0305'
--客户退换货查询
update EmployeePower SET moduleid ='1610'  where moduleid ='030609'
--经营报表
update EmployeePower SET moduleid ='1614'  where moduleid ='0310'

--商品采购统计
update EmployeePower SET moduleid ='021107'  where moduleid ='0204'
--采购汇总分析
update EmployeePower SET moduleid ='021112'  where moduleid ='0209'
--供应商供货统计
update EmployeePower SET moduleid ='021109'  where moduleid ='0205'
--商品采购分析
update EmployeePower SET moduleid ='021110'  where moduleid ='0206'
--采购建议表
update EmployeePower SET moduleid ='021111'  where moduleid ='0208'

*/



GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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

 
  
--  ********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：F_AccountYearCfg                                       
--  ||   过程功能：Pos收银流水查询  
--  ||   modify by 老罗 2012-11-09  
--  ||==========================================================================================  
CREATE PROCEDURE GP_PosCashStat_NEW  
    (  
      @SaleDateBegin VARCHAR(10),  
      @SaleDateEnd VARCHAR(10),  
      @SaleTimeBegin VARCHAR(8),  
      @SaleTimeEnd VARCHAR(8),  
      @BillCode VARCHAR(200),  
      @PosName VARCHAR(30),  
      @ktypeid VARCHAR(50),  
      @CashierETypeID VARCHAR(50),  
      @SalesManETypeID VARCHAR(50),  
      @VipNo VARCHAR(18),  
      @Draft VARCHAR(8), --传的值: -1(全部),0(POS小票),1(草稿),2(过账)     
      @BranchID VARCHAR(50),  
      @OperatorID VARCHAR(50)  
    )  
AS  
  
 DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int   
 EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output   
  
    DECLARE @DateTimeBegin VARCHAR(30),  
        @DateTimeEnd VARCHAR(30),  
        @sql VARCHAR(4000)      
    SET @DateTimeBegin = @SaleDateBegin + ' ' + @SaleTimeBegin      
    SET @DateTimeEnd = @SaleDateEnd + ' ' + @SaleTimeEnd     
      
 IF object_id('tempdb..#Emp') is not null     
 drop table #Emp  
 SELECT typeid,FullName INTO #Emp   FROM dbo.FN_GetPowerRangeEList(@OperatorID,'')  
  
   
 IF object_id('tempdb..#keyEmp') is not null     
 drop table #keyEmp  
 SELECT tbl.keyId,tbl.Salesman,tbl.Salesmanid  
 INTO #keyEmp  
 FROM  
 (  
  SELECT DISTINCT si.keyId,ee.FullName AS Salesman,ee.TypeId AS Salesmanid  
  FROM dbo.tpx_SaleIndex si  
  INNER JOIN dbo.tpx_SaleList sl ON si.keyId = sl.ZBKeyId  
  INNER JOIN dbo.tpx_SaleManList sml ON sml.CBKeyId = sl.keyid  
  INNER JOIN #Emp ee ON ee.TypeId = sml.ETypeId  
  WHERE si.SaleTime BETWEEN @DateTimeBegin AND @DateTimeEnd  
 ) tbl  
   
 --删除未包含在营业员筛选条件中的数据  
 DELETE FROM #keyEmp WHERE keyId NOT IN   
 (  
  SELECT DISTINCT keyId FROM #keyEmp  
  WHERE Salesmanid LIKE @SalesManETypeID + '%'  
 )  
   
 IF object_id('tempdb..#keyEmp1') is not null     
 drop table #keyEmp1  
 SELECT tbl1.keyId,tbl1.Salesman  
 INTO #keyEmp1  
 FROM(  
 SELECT ke.keyId,Salesman = STUFF((SELECT ',' + kee.Salesman FROM #keyEmp kee WHERE kee.keyId = ke.keyid ORDER BY kee.keyId FOR XML PATH('')),1,1,'')  
 FROM #keyEmp ke GROUP BY ke.keyId) tbl1  
  
 IF object_id('tempdb..#ktype') is not null     
 drop table #ktype  
 SELECT KtypeId INTO #ktype FROM FN_GetStockListOfBranch(@OperatorID,@BranchID,@ktypeid)  

IF object_id('tempdb..#saleindex') is not null     
drop table #saleindex  
SELECT keyId,SaleTime,PosVchCode,
    BillCode,Total,BillDiscount,
    RetReplaCashSum,Cashier,PosID,
    KtypeID,Draft,DraftVchcode,VipCardID,
    FinallyTotal,JTypeId
INTO #saleindex
FROM dbo.tpx_SaleIndex C
WHERE EXISTS(SELECT 1 FROM #ktype br WHERE br.KtypeId = C.ktypeid OR C.ktypeid = '')  
AND C.VtypeId = '00001'  --仅统计零售单据  
AND C.SaleTime BETWEEN @DateTimeBegin AND @DateTimeEnd  
AND C.Cashier LIKE @CashierETypeID+'%'  
AND C.BillCode LIKE '%' + @BillCode + '%'  
AND EXISTS(SELECT 1 FROM #Emp ep WHERE ep.typeid = c.Cashier)  
AND EXISTS(SELECT 1 FROM #keyEmp kep WHERE kep.keyid = C.keyid)  

 IF object_id('tempdb..##CommonPosSaleIndextemp') is not null     
 drop table #CommonPosSaleIndextemp  
    CREATE TABLE #CommonPosSaleIndextemp  
        (  
          POSVchCode INT,  
          BillCode VARCHAR(200),  
          SaleDate DATETIME,  
          Total numeric(24,10),  
          BillDisCount numeric(24,10),  
          RetReplaceCashSum numeric(24,10),  
          Cashier VARCHAR(100),  
          Salesman VARCHAR(100),  
          PosID VARCHAR(100),  
          ktypeid VARCHAR(50),  
          Draft INT,  
          DraftVchcode INT,  
          VipCardID INT,  
          SaleType VARCHAR(40),  
          GatheringMoney numeric(24,10),    
          GatheringVipID VARCHAR(50),  
          yhtotal numeric(24,10)  
        )    
          
 /*      
 把原来的4个收款的列，改成行，让用户看见 SELECT * FROM CommonPosSaleIndex      
 */  
   
 INSERT INTO #CommonPosSaleIndextemp  
    SELECT  C.PosVchCode,  
            C.BillCode,  
            C.SaleTime AS 'SaleDate',  
            C.Total,  
            CASE WHEN C.Total<0 THEN -C.BillDisCount ELSE C.BillDisCount END AS BillDisCount,  
            C.RetReplaCashSum AS RetReplaceCashSum,  
            C.Cashier,  
            --C.Salesman,  
            (SELECT kep.Salesman FROM #keyEmp1 kep WHERE kep.keyId = C.keyId) AS Salesman,  
            C.PosID,  
            C.ktypeid,  
            C.Draft,  
            C.DraftVchcode,  
            C.VipCardID,  
            SaleType,  
            GatheringMoney,  
            GatheringVipID,  
            yhtab.yhtotal1 - C.FinallyTotal AS yhtotal  
    FROM    #saleindex C  
            INNER JOIN (
                SELECT I.keyId,  
                (SELECT pcc.AtypeName FROM tpx_PosCashTypeConfig pcc WHERE pcc.Keyid = L.Akeyid AND pcc.Jtypeid = I.jtypeid) AS SaleType,  
				SUM(ISNULL(L.[Total],0)) GatheringMoney,  
				'' GatheringVipID  
				FROM #saleindex I LEFT JOIN tpx_SalePayList L  ON L.ZBKeyId=I.keyId  
				WHERE ISNULL(L.AKeyId,'') <> '00004'
				GROUP BY AKeyId,I.keyId,[VIPId],JTypeId   
            ) #tab ON C.keyId = #tab.keyId  
            INNER JOIN 
			(
			    SELECT ROUND(SUM(CONVERT(NUMERIC(24,10),tpx_sl.Qty)* CONVERT(NUMERIC(24,10),tpx_sl.RetailPrice)),@dig_total) AS yhtotal1,
				tpx_sl.zbkeyid  
                FROM dbo.tpx_SaleList tpx_sl  
                GROUP BY tpx_sl.ZBKeyId  
            ) yhtab ON yhtab.zbkeyid = C.keyId  
      
    INSERT INTO #CommonPosSaleIndextemp  
    SELECT C.PosVchCode,  
            C.BillCode,  
            C.SaleTime AS 'SaleDate',  
            C.Total,  
            CASE WHEN C.Total<0 THEN -C.BillDisCount ELSE C.BillDisCount END AS BillDisCount,  
            C.RetReplaCashSum AS RetReplaceCashSum,  
            C.Cashier,  
            --C.Salesman,  
            (SELECT kep.Salesman FROM #keyEmp1 kep WHERE kep.keyId = C.keyId) AS Salesman,  
            C.PosID,  
            C.ktypeid,  
            C.Draft,  
            C.DraftVchcode,  
            C.VipCardID,  
            SaleType,  
            CASE WHEN  C.Total < 0 THEN  -GatheringMoney ELSE GatheringMoney END GatheringMoney,  
            GatheringVipID,  
            yhtab.yhtotal1 - C.FinallyTotal AS yhtotal  
    FROM    #saleindex C  
            INNER JOIN (SELECT I.keyId,  
            (SELECT pcc.AtypeName FROM tpx_PosCashTypeConfig pcc WHERE pcc.Keyid = tsml.Akeyid AND pcc.Jtypeid = I.jtypeid) AS SaleType,  
            SUM(ISNULL(L.[Total],0)) GatheringMoney,  
            L.[VIPId] GatheringVipID  
                                 FROM #saleindex I LEFT JOIN dbo.tpx_SaleVipList L ON L.ZBKeyId=I.keyId  
                                 INNER JOIN dbo.tpx_SalePayList tsml ON I.keyId = tsml.ZBKeyId  
                                 WHERE tsml.AKeyId = '00004'
                                 GROUP BY I.keyId,L.[VIPId],JTypeId,tsml.AKeyId   
                       ) #tab ON C.keyId = #tab.keyId  
            INNER JOIN (SELECT ROUND(SUM(CONVERT(NUMERIC(24,10),tpx_sl.Qty)* CONVERT(NUMERIC(24,10),tpx_sl.RetailPrice)),@dig_total) AS yhtotal1,tpx_sl.zbkeyid  
            FROM dbo.tpx_SaleList tpx_sl
            GROUP BY tpx_sl.ZBKeyId  
            ) yhtab ON yhtab.zbkeyid = C.keyId  
  
       SET @sql = '
        IF object_id(''tempdb..##NewTable'') is not null     
           drop table ##NewTable  
       SELECT a.PosVchCode,a.BillCode,SaleDate,        
         a.Total,BillDisCount,RetReplaceCashSum,SaleType,GatheringMoney,GatheringVipID,        
         Cashier,Salesman,a.yhtotal,  
         --(select ISNULL(vc.CardNo,'''') from VipCards vc where vc.CardID = vipcardid) as VipCardID,   
		 right(''0000000000''+cast(vipcardid as varchar),10) as VipCardID,
         ISNULL(a.ktypeid,'''') AS sFullname,       
         ISNULL(po.Fullname,'''') AS posFullname,--V.CardNo AS cardno,--  
         --ISNULL(V.CardNo,'''') AS CardNo,
		 right(''0000000000''+cast(GatheringVipID as varchar),10) as CardNo,
         a.draft,a.DraftVchcode                   
         INTO ##NewTable            
  FROM #CommonPosSaleIndextemp a            
       --LEFT JOIN stock st   ON a.ktypeid=st.typeid  and st.deleted=0                    
       LEFT JOIN tpx_PosInfo   po   ON a.PosID=po.PosID             
       --LEFT JOIN VipCards V ON a.GatheringVipID=V.CardID  
  WHERE BillCode like ''%' + @BillCode + '%''            
        AND ISNULL(po.Fullname,'''') like ''%' + @PosName + '%'''  
      
    SET @sql = @sql + ' Order by a.PosVchCode'      
       
    EXEC (@sql)      
      
    SELECT  PosVchCode,  
            BillCode,  
            SaleDate,  
            Total,  
            BillDisCount,  
            RetReplaceCashSum,  
            SaleType,  
            GatheringMoney,  
            GatheringVipID,  
            Cashier,  
            Salesman,  
            sFullname,  
            posFullname,  
            CardNo,  
            draft,  
            DraftVchcode,  
            yhtotal,  
            VipCardID  
    INTO    #PosUserReturnTable  
    FROM    ( SELECT    PosVchCode,  
                        BillCode,  
                        SaleDate,  
                        Total,  
                        BillDisCount,  
                        RetReplaceCashSum,  
                        SaleType,  
                        GatheringMoney,  
                        GatheringVipID,  
                        E.fullname AS Cashier,  
                        Salesman,  
                        sFullname,  
                        posFullname,  
                        CardNo,  
                        N.draft,  
                        n.DraftVchcode,  
                        yhtotal,  
                        VipCardID  
              FROM      ##NewTable N  
                        LEFT JOIN Employee E ON N.Cashier = E.typeid  
                                                AND E.deleted = 0  
            ) A  
    ORDER BY PosVchCode    
    
    SELECT  IDENTITY( NUMERIC(9),1,1 ) AS NoID,  
            BillCode,  
            SaleDate,  
            Total,  
            BillDisCount,  
            RetReplaceCashSum,  
            SaleType,  
            GatheringMoney,  
            GatheringVipID,  
            Cashier,  
            Salesman,  
            sFullname,  
            posFullname,  
            CardNo,  
            draft,  
            DraftVchcode,  
            posvchcode,  
            yhtotal,  
            VipCardID  
    INTO    #PosUserReturnTable2  
    FROM    #PosUserReturnTable  
    WHERE   PosVchCode IN ( SELECT  PosVchCode  
                            FROM    #PosUserReturnTable  
                            WHERE   CardNo LIKE '%' + @VipNo + '%' )  --只要储值卡查询有一条，该张收银的信息全部都要显示    
    ORDER BY PosVchCode,SaleDate    
    
    DROP TABLE ##NewTable  
    DROP TABLE #CommonPosSaleIndextemp  
    --DROP TABLE ##CommonPosSaleIndex      
    DROP TABLE #PosUserReturnTable      
        
    CREATE TABLE #PosUserReturnTable1  
        (  
          NoID NUMERIC(9),  
          BillCode VARCHAR(200),  
          SaleDate DATETIME,  
          Total numeric(24,10),  
          BillDisCount numeric(24,10),  
          RetReplaceCashSum numeric(24,10),  
          SaleType VARCHAR(40),  
          GatheringMoney numeric(24,10),    
 --SaveAccountCardNo varchar(100),    
          Cashier VARCHAR(100),  
          Salesman VARCHAR(100),  
          sFullname VARCHAR(100),  
          posFullname VARCHAR(100),  
          CardNo VARCHAR(100),  
          draft INT,  
          DraftVchcode INT,  
          posvchcode NUMERIC(18, 0),  
          yhtotal NUMERIC(24, 10),  
          VipCardID VARCHAR(1000)  
        )    
    
/*    
直接在储存过程中处理，如果Pos小票中，BillCode和销售时间一起有相同的，就以第一条记录显示完整，其他的只保留 收款方式(SaleType)  收款金额(GatheringMoney)  收款卡号(SaveAccountCardNo)     
*/    
    DECLARE @OLDBillCode VARCHAR(200)    
    DECLARE @NewNoID NUMERIC(9)    
    DECLARE @OLDSaleDate DATETIME   --以前只判断 BillCode 相同，就能确定单据是否是同一张，（由于不同单据的BillCode经常重复，现在在加上销售时间进行区别 ）    
    
    DECLARE @NoID1 NUMERIC(9),  
        @BillCode1 VARCHAR(200),  
        @SaleDate1 DATETIME,  
        @Total1 numeric(24,10),  
        @BillDisCount1 numeric(24,10),  
        @RetReplaceCashSum1 numeric(24,10),  
        @SaleType1 VARCHAR(40),  
        @GatheringMoney1 numeric(24,10),    
 --@SaveAccountCardNo1 varchar(100),    
        @Cashier1 VARCHAR(100),  
        @Salesman1 VARCHAR(100),  
        @sFullname1 VARCHAR(100),  
        @posFullname1 VARCHAR(100),  
        @CardNo1 VARCHAR(100),  
        @draftflag INT,  
        @DraftVchcodeflag INT,  
        @posvchcode NUMERIC(18, 0),    
  @yhtotal1 numeric(24,10),  
  @VipCardID varchar(1000)  
  
  
  INSERT  INTO #PosUserReturnTable1  
  
  select			
	NoID,  
	BillCode,  
	SaleDate,  
	Total,  
	BillDisCount,  
	RetReplaceCashSum,  
	SaleType,  
	GatheringMoney,  
	Cashier,  
	Salesman,  
	sFullname,  
	posFullname,  
	CardNo,  
	draft,  
	DraftVchcode,  
	posvchcode,  
	yhtotal,  
	VipCardID
	FROM (
					  SELECT			
						NoID,  
						BillCode,  
						SaleDate,  
						Total,  
						BillDisCount,  
						RetReplaceCashSum,  
						SaleType,  
						GatheringMoney,  
						Cashier,  
						Salesman,  
						sFullname,  
						posFullname,  
						CardNo,  
						draft,  
						DraftVchcode,  
						posvchcode,  
						yhtotal,  
						VipCardID,
						ROW_NUMBER() OVER(PARTITION BY saledate,BillCode ORDER BY saledate,BillCode) AS 'RowNumber'
						FROM    #PosUserReturnTable2     
				)      x      where RowNumber=1
     
  INSERT  INTO #PosUserReturnTable1                                    
select			
	noid,  
  '',  
  NULL,  
  NULL,  
  NULL,  
  NULL,  
  SaleType,  
  GatheringMoney,  
  '',  
'',  
  '',  
  '',  
  CardNo,  
  1,  
  DraftVchcode,  
  posvchcode,  
  NULL,  
  NULL  
	FROM (
					  SELECT			
						NoID,  
						BillCode,  
						SaleDate,  
						Total,  
						BillDisCount,  
						RetReplaceCashSum,  
						SaleType,  
						GatheringMoney,  
						Cashier,  
						Salesman,  
						sFullname,  
						posFullname,  
						CardNo,  
						draft,  
						DraftVchcode,  
						posvchcode,  
						yhtotal,  
						VipCardID,
						ROW_NUMBER() OVER(PARTITION BY saledate,BillCode ORDER BY saledate,BillCode) AS 'RowNumber'
						FROM    #PosUserReturnTable2     
				)      x      where RowNumber<>1				
				
			
  
  
    IF @Draft = '-1'   
        BEGIN  
            SELECT  noid,  
                    BillCode,  
                    CONVERT(VARCHAR(20),SaleDate,20) SaleDate,  
                    a.Total,  
                    BillDisCount,  
                    RetReplaceCashSum,  
                    SaleType,  
                    GatheringMoney,  
                    Cashier,  
                    Salesman,  
                    sFullname,  
                    posFullname,  
                    CardNo,  
                    --CASE draft WHEN 0 THEN 'POS小票' WHEN 1 THEN '草稿' WHEN 2 THEN '过账' ELSE '' END AS draft, --传的值: -1(全部),0(POS小票),1(草稿),2(过账),  
                    CASE billcode WHEN '' THEN '' ELSE  
                    CASE ISNULL(CAST(a.draft AS VARCHAR), 'X')  
                      + ISNULL(CAST(b.Draft AS VARCHAR), 'X')  
                      WHEN '0X' THEN 'POS小票'  
                      WHEN 'XX' THEN 'POS小票'  
                      WHEN '12' THEN '过账'  
                      WHEN '22' THEN '过账'  
                      WHEN 'X2' THEN '过账'  
                      ELSE '草稿'  
                    END   
                    END AS draft,  
                    b.Draft AS dlyndxdraft,  
                    DraftVchcode,  
                    posvchcode,  
                    yhtotal,  
                    a.VipCardID  
            FROM    #PosUserReturnTable1 a  
                    LEFT JOIN dbo.DlyNdx b ON a.DraftVchcode = b.Vchcode     
                    order by noid
        END     
      
    ELSE   
        BEGIN  
            IF @Draft = '0'   
                SET @Draft = 'POS小票'  
            IF @Draft = '1'   
                SET @Draft = '草稿'  
            IF @Draft = '2'                   SET @Draft = '过账'  
  
            SELECT  noid,  
                    BillCode,  
                    CONVERT(VARCHAR(20),SaleDate,20) SaleDate,  
                    a.Total,  
                    BillDisCount,  
                    RetReplaceCashSum,  
                    SaleType,  
                    GatheringMoney,  
                    Cashier,  
                    Salesman,  
                    sFullname,  
                    posFullname,  
                    CardNo,  
                    --CASE draft WHEN 0 THEN 'POS小票' WHEN 1 THEN '草稿' WHEN 2 THEN '过账' ELSE '' END AS draft, --传的值: -1(全部),0(POS小票),1(草稿),2(过账),  
                    CASE billcode WHEN '' THEN '' ELSE  
                    CASE ISNULL(CAST(a.draft AS VARCHAR), 'X')  
                      + ISNULL(CAST(b.Draft AS VARCHAR), 'X')  
                      WHEN '0X' THEN 'POS小票'  
                      WHEN 'XX' THEN 'POS小票'  
                      WHEN '12' THEN '过账'  
                      WHEN '22' THEN '过账'  
                      WHEN 'X2' THEN '过账'  
                      ELSE '草稿'  
                    END   
                    END AS draft,  
                    b.Draft AS dlyndxdraft,  
                    DraftVchcode,  
                    posvchcode,  
                    yhtotal,  
                    a.VipCardID  
            FROM    #PosUserReturnTable1 a  
                    LEFT JOIN dbo.DlyNdx b ON a.DraftVchcode = b.Vchcode  
            WHERE   CASE ISNULL(CAST(a.draft AS VARCHAR), 'X')  
                      + ISNULL(CAST(b.Draft AS VARCHAR), 'X')  
                      WHEN '0X' THEN 'POS小票'  
                      WHEN 'XX' THEN 'POS小票'  
                      WHEN '12' THEN '过账'  
                      WHEN '22' THEN '过账'  
                      WHEN 'X2' THEN '过账'  
                      ELSE '草稿'  
                    END = @Draft  
                     order by noid
        END  
        --PRINT @draft  
          
    DROP TABLE #PosUserReturnTable1    
    DROP TABLE #PosUserReturnTable2    
    DROP TABLE #keyEmp  
    DROP TABLE #keyEmp1  
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/******************************************20130508********************************************/

if not exists(SELECT 1 FROM SYSOBJECTS T1 INNER JOIN SYSCOLUMNS T2 ON T1.ID=T2.ID WHERE T1.NAME='dztconfig' AND T2.NAME='AtypeSKZF')
BEGIN
	alter table dztconfig
	add AtypeSKZF varchar(50)--收款账户
END

if not exists(SELECT 1 FROM SYSOBJECTS T1 INNER JOIN SYSCOLUMNS T2 ON T1.ID=T2.ID WHERE T1.NAME='dztconfig' AND T2.NAME='AtypeFKZF')
BEGIN
	alter table dztconfig
	add AtypeFKZF varchar(50)--付款账户
END

/******************************************20130513********************************************/
/******************************************20130604********************************************/
if not exists(select 1 from syscon where [order]=250)
insert into syscon([order],[name],[stats],number)
values(250,'物流单据明细格式下显示条码',0,1)
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


--  ********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：F_S_GetUser                                                 
--  ||   过程功能：系统设置－－用户设置（读）  
--  ||=========================================================================================  
--  ||   参数说明：  参数名称         类型            意义                     输入输出  
--  ||            -----------------------------------------------------------------------------  
--  ||        @cMode             int         1:录帐配置，2:查帐配置，3:其它配置  
--  ||          
--  ||=========================================================================================     
--  ||   返回值：         值                                     说明  
--  ||       ----------------------------------------------------------------------------------------  
--  ||      
--  ||==========================================================================================  
CREATE PROCEDURE FZGetUser  
(
	@cMode	int   
)  
AS  

--113 系统允许可发货库存为负库存 此配置默认为允许，不显示出来

if @cMode = 1
  select [order],[name],[stats] From syscon Where number =@cmode and [order] not IN (2,3,5,21,103,108,115,113) order by [order]   
ELSE IF @cMode = 2
  select [order],[name],[stats] From syscon Where number =@cmode and [order] not in (2,3,5,21,103,108,115,113,37,70,105) order by [order]
ELSE IF @cMode = 3
  select [order],[name],[stats] From syscon WHERE Number IN (1,2,3) AND [order] IN (13,14,22,33,36,70,81,82,89,104,107,109,111,114,140,141,142,143,144,145,146,240,250) ORDER BY [name]

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--UpToPubSql
--订货会日志表
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MpoImport]') AND type in (N'U'))
CREATE TABLE [dbo].[MpoImport](
	[MpoBillNo] [bigint] NULL,
	[MpoBillCode] [varchar](100) NULL,
	[MpoId] [varchar](50) NULL,
	[MpoName] [varchar](200) NULL,
	[BillNo] [bigint] NULL,
	[BillCode] [varchar](100) NULL,
	[TypeNo] [char](5) NULL,
	[ImportTime] [datetime] NULL,
	[OprId] [int] NULL
) ON [PRIMARY]

GO

--订货会菜单控制
IF NOT EXISTS(SELECT 1 FROM dbo.SysData WHERE SubName='mposetting')
INSERT INTO dbo.SysData(SubName, SubValue, SubComment )VALUES  ( 'mposetting','0', '订货会是否在菜单中显示')
GO

IF NOT EXISTS(SELECT 1 FROM dbo.SysData WHERE SubName='mpourl')
INSERT INTO dbo.SysData(SubName, SubValue, SubComment )VALUES  ( 'mpourl','', '订货会最近一次网址')
GO

IF NOT EXISTS(SELECT 1 FROM dbo.SysData WHERE SubName='mpopwd')
INSERT INTO dbo.SysData(SubName, SubValue, SubComment )VALUES  ( 'mpopwd','', '订货会最近一次登录验证码')
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

  --加入订货会相关
IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZSystemReset]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZSystemReset]
GO
--  ********************************************************************************************
--  ||                                                                                        
--  ||  过程名称：FZSystemReset                                     
--  ||  过程功能：系统重建
--  ||  清除Price 中的已经删除的商品，单位
--  ||	清除GoodsStocks 中的已经删除的商品，仓库
--  ||	清除IniGoodsStocks 中的已经删除的商品，仓库
--  ||	清除 Atype, Ptype, Btype, Employee, Stock 中已经删除的记录
--  ||	清除明细帐本库， 索引库， 库存数量库
--  ||	清除定单库，零售单库
--  ||	清除 SYSDATA中的确认期初标志
--  ||	清除 SYSDATA中的确认期号标志
--  ||	
--  ||	如果要清除期初，就清除期初库存库，清除ATYPE， BTYPE 中的科目期初和应收应付
--  ||	如果要清除草稿，就清除草稿库
--  ||=========================================================================================
--  ||   参数说明：  参数名称         类型            意义                     输入输出
--  ||            -----------------------------------------------------------------------------
--  ||              @Period              varchar(5),        是否清除期初值
--  ||  	    @BakDly            varchar(5),        是否清除草稿
--  ||              @BasicInf           varchar(5)         是否清除基本信息
--  ||              @CX                   varchar(5)         是否清除促销设置
--  ||=========================================================================================   
--  ||   返回值：         值                                     说明
--  ||----------------------------------------------------------------------------------------
--  ||                    0                               执行成功
--  ||                  －1                               执行失败
--  ||==========================================================================================

/*
作者：cqhua
日期：2011-08-18
修改原因：VipIntegralPtypeDetail --清除VIP商品积分明细
*/

CREATE  PROCEDURE FZSystemReset
    (
      @Period VARCHAR(5),
      @BakDly VARCHAR(5),
      @BasicInf VARCHAR(5),
      @CX VARCHAR(5),
      @ifstop VARCHAR(5),
      @ifvip VARCHAR(5),
      @ifDD VARCHAR(5)
    )
AS 
    SET NOCOUNT ON
    DECLARE @SQL VARCHAR(500)
    DECLARE @szTemp VARCHAR(50)
    DECLARE @ret INT
    BEGIN TRAN DELBILL


--清楚往来单位可换货额和数量
            DELETE  FROM btyperettotal
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM btyperetqty
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE ChangeBillNdx
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE ChangeBillData
            IF @@error <> 0 
                GOTO error1	
                    
  truncate table OrderVchcodeToQty
  
  TRUNCATE TABLE GoodsstockBackupRecord

--清除促销
    TRUNCATE TABLE CX_SALESTOCKSAREA
    TRUNCATE TABLE CX_COMBINATIONDETAILBILL
    TRUNCATE TABLE CX_COMBINATIONBILL
    TRUNCATE TABLE CX_LARGESSBILL
    TRUNCATE TABLE CX_SALEBYHAND
    TRUNCATE TABLE CX_SPECIALOFFERBILL
    TRUNCATE TABLE CX_SALEPLANINDEX

-- 清除POS小票及挂单(老的)
    TRUNCATE TABLE COMMONPOSSALELIST
    TRUNCATE TABLE COMMONPOSSALEINDEX
    TRUNCATE TABLE COMMONPOSSALELISTFREEZE
    TRUNCATE TABLE COMMONPOSSALEINDEXFREEZE
    TRUNCATE TABLE PosVipMoneyList 
    ---pos单据相关（新的4.1）
    TRUNCATE TABLE dbo.tpx_SaleIndex
    TRUNCATE TABLE dbo.tpx_SaleList
    TRUNCATE TABLE dbo.tpx_ReplenishList
    TRUNCATE TABLE dbo.tpx_SalePayList
    TRUNCATE TABLE dbo.tpx_SaleVipList
    TRUNCATE TABLE dbo.tpx_SaleManList

    --pos促销相关（新的4.1）
    TRUNCATE TABLE dbo.tpx_CXBillBound
    TRUNCATE TABLE dbo.tpx_CXBillCom
    TRUNCATE TABLE dbo.tpx_CXBillComD
    TRUNCATE TABLE dbo.tpx_CXBillHand
    TRUNCATE TABLE dbo.tpx_CXBillIndex
    TRUNCATE TABLE dbo.tpx_CXBillLarg
    TRUNCATE TABLE dbo.tpx_CXBillSpec
    TRUNCATE TABLE dbo.tpx_CXSpecialPtype
    --pos盘点相关（新的4.1）
    TRUNCATE TABLE dbo.tpx_CheckList
    TRUNCATE TABLE dbo.tpx_CheckNdx
    TRUNCATE TABLE dbo.tpx_CheckPointNdx
    TRUNCATE TABLE dbo.tpx_BillMaxNo
    TRUNCATE TABLE dbo.tpx_BillNoPool
    --订货会日志表
    TRUNCATE TABLE dbo.MpoImport
	--智能配货相关的暂存数据表
    TRUNCATE TABLE AutoPhTitleData
    TRUNCATE TABLE AutoPhGrdData
    TRUNCATE TABLE AutoPhOrderTitleData
    TRUNCATE TABLE AutoPhOrderGrdData
    
    --清除店帐通表
    --TRUNCATE TABLE dbo.DZTConfig
    TRUNCATE TABLE dbo.DZTVchcode

    --清除库龄分析作业表
    TRUNCATE TABLE dbo.StockAgeDetail  
    
	--清全能进销存作业表
	TRUNCATE TABLE TableForAllJXC
	Update QueryVchcodeRec set subvalue = '0' where subname = 'AllPowerMaxVch'

            TRUNCATE TABLE  xw_operLogCheck
            IF @@error <> 0 
                GOTO error1	          
                
--清除POS盘点单
    DELETE  FROM CommonPosPtypeCheckNdx
    DELETE  FROM CommonPosPtypeCheckList

    TRUNCATE TABLE PtypeUniqueCode  --商品唯一码记录表
    TRUNCATE TABLE PtypeUniqueCheck --商品唯一码校验表


--	删除客户价格跟踪库，期初库存库，借进借出库中已删除的商品，仓库，客户
    UPDATE  ptype
    SET     recPrice = 0
    IF @@error <> 0 
        GOTO error1	
------------------------------------------------------------------ 清除零售表        

  -------------------- 清除单据最大编号
    TRUNCATE TABLE Billdaynumber
    IF @@error <> 0 
        GOTO error1
    TRUNCATE TABLE Billmonthnumber
    IF @@error <> 0 
        GOTO error1
	
    UPDATE  vchtype
    SET     SNMAX = 0
    FROM    vchtype 
    IF @@error <> 0 
        GOTO error1
	   
    UPDATE  sysdata
    SET     SubValue = 0
    WHERE   subname = 'SNMax'
    IF @@error <> 0 
        GOTO error1
    TRUNCATE TABLE  POSRetailBill
    IF @@error <> 0 
        GOTO error1	
    TRUNCATE TABLE  POSRetailBillFreeze
    IF @@error <> 0 
        GOTO error1	
		--  truncate table  Pos
    --	if @@error<>0 goto error1	
    TRUNCATE TABLE  PosRetailBillDetail
    IF @@error <> 0 
        GOTO error1	
    TRUNCATE TABLE  PosRetailBillDetailFreeze
    IF @@error <> 0 
        GOTO error1	
    TRUNCATE TABLE  Shift
    IF @@error <> 0 
        GOTO error1	
 -- truncate table  Shift
	--  if @@error<>0 goto error1	
    DELETE  FROM Pos
    WHERE   deleted = 1
    IF @@error <> 0 
        GOTO error1	
    DELETE  FROM Site
    WHERE   deleted = 1
    IF @@error <> 0 
        GOTO error1	
	--  truncate table  Site
    --	if @@error<>0 goto error1	
-------------------------------------------------------------------------清除库存备份表
    TRUNCATE TABLE GoodsstockBackup
    IF @@error <> 0 
        GOTO error1
-------------------------------------------------------------------------清除所有订单的到货数量
-- 	update dlyndxorder set userover=0 
-- 	if @@error<>0 Goto error1
-- 	Update bakdlyorder set toqty=0 ,isover=0
-- 	if @@error<>0 Goto error1
-- 	Update orderdetail set toqty=0
-- 	if @@error<>0 Goto error1

    UPDATE  dlyndxorder
    SET     userover = 0,
            isover = 0,
            TransferNumber = 0 --强制完成，是否完成，使用次数都清0
    IF @@error <> 0 
        GOTO error1
    UPDATE  bakdlyorder
    SET     toqty = 0, isover = 0
    IF @@error <> 0 
        GOTO error1
    UPDATE  bakdlyorderdetail
    SET     toqty = 0
    IF @@error <> 0 
        GOTO error1
--------------------------------------------------------------------------
--删除垃圾消息
DELETE FROM xw_message WHERE MSGAddtion = '' OR CHARINDEX(';',MSGAddtion) = 0 
DELETE from xw_message WHERE CAST(SUBSTRING(MSGAddtion,1,CHARINDEX(';',MSGAddtion) - 1) AS INT) NOT IN (SELECT vchcode FROM dbo.DlyNdx) 
-------------------------------------------------------------------------清除期初库存表	
    TRUNCATE TABLE PriceTrace
    IF @@error <> 0 
        GOTO error1
    TRUNCATE TABLE AuditingBill --清除审核过程表
    IF @@error <> 0 
        GOTO error1
    UPDATE  ptype
    SET     recprice1 = 0 
    IF @@error <> 0 
        GOTO error1
    UPDATE  ptype
    SET     recprice = 0
    IF @@error <> 0 
        GOTO error1
    DELETE  IniGoodsdetail
    FROM    IniGoodsdetail,
            IniGoodsstocks,
            ptype
    WHERE   IniGoodsstocks.[ptypeid] = ptype.[typeid]
            AND ptype.[deleted] = 1
            AND IniGoodsdetail.orderid = IniGoodsstocks.orderid 
    IF @@error <> 0 
        GOTO error1		
    DELETE  IniGoodsstocks
    FROM    IniGoodsstocks
            INNER JOIN ptype ON IniGoodsstocks.[ptypeid] = ptype.[typeid]
    WHERE   ptype.[deleted] = 1
    IF @@error <> 0 
        GOTO error1		
    DELETE  IniGoodsdetail
    FROM    IniGoodsdetail,
            IniGoodsstocks,
            Stock
    WHERE   IniGoodsstocks.[ktypeid] = stock.[typeid]
            AND stock.[deleted] = 1
            AND IniGoodsdetail.orderid = IniGoodsstocks.orderid
    IF @@error <> 0 
        GOTO error1	
    DELETE  IniGoodsstocks
    FROM    IniGoodsstocks
            INNER JOIN Stock ON IniGoodsstocks.[ktypeid] = stock.[typeid]
    WHERE   stock.[deleted] = 1
    IF @@error <> 0 
        GOTO error1		
	
-------------------------------------------------------------------------------清除草稿表
    DELETE  FROM bakdlydetail
    WHERE   dlyorder IN ( SELECT    dlyorder
                          FROM      bakdly
                          WHERE     vchtype = 230 )
    IF @@error <> 0 
        GOTO error1	
    DELETE  FROM bakdly
    WHERE   vchtype = 230
    IF @@error <> 0 
        GOTO error1	
------------------------------------------------------------------------------
    DELETE  FROM dlyndx
    WHERE   vchtype = 230
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------清除Vip相关表		
    DECLARE @UpdateTag INT  
    EXEC [dbo].[XW_GetUpdateTag] 'VipCards', @UpdateTag OUTPUT		
    UPDATE  Vipcards
    SET     allConsume = 0,
            allintegral = 0,
            dointegral = 0,
            undointegral = 0,
            backtotal = 0,
            LastDate = '',
            LastTotal = 0,
            LastRate = 0,
            LastDiscountTotal = 0,
            NowTotal = 0,
            NowRate = 0,
            NowDiscountTotal = 0,
            PeriodTotal = 0,
            ConsumeAbility = 0,
            favourable = 0,
            UndoTotal = 0,
            LJXFJFJE = 0,
            Savemoney = 0,
            UpdateTag = @UpdateTag
    IF @@error <> 0 
        GOTO error1	
    DELETE  vipcards
    WHERE   deleted = 1
    IF @@Error <> 0 
        GOTO error1
    TRUNCATE TABLE VIpCardIntegralTransact
    IF @@error <> 0 
        GOTO error1	
    TRUNCATE TABLE	VIPCardIntegralSend
    IF @@error <> 0 
        GOTO error1	
    TRUNCATE TABLE	vipintegraldetail --清除积分历史
    IF @@error <> 0 
        GOTO error1	
    TRUNCATE TABLE VipIntegralPtypeDetail --清除VIP商品积分明细
    IF @@error <> 0 
        GOTO error1	

    TRUNCATE TABLE  CardFillList --清除储值历史
    IF @@error <> 0 
        GOTO error1
    UPDATE  Vipcards
    SET     iftransfered = 0
    IF @@error <> 0 
        GOTO error1
  ----重新插入期初
    INSERT  INTO VIPIntegralDetail
            (
              ktypeid,
              BatchNo,
              ConsumeAdd,
              IntegralAdd,
              AddFlag,
              CardID,
              date,
              vchcode,
              ConsumeTotal,
              IntegralConsume,
              Integral,
              IntegralTotal
            )
            SELECT  '00001',
                    -1,
                    ISNULL(b.allconsume, 0),
                    ISNULL(b.integral2, 0),
                    ISNULL(b.ExpandNo, 0),
                    a.cardid,
                    CONVERT(VARCHAR(10), GETDATE(), 120),
                    0,
                    a.allconsume,
                    a.ljxfjfje,
                    a.allintegral,
                    a.allintegral
            FROM    vipcards a
                    LEFT JOIN vipcardexpand b ON a.cardtypeid = b.cardid   
    IF @@error <> 0 
        GOTO error1	
----------------------------------------------------------------------------清除往来单位
--print('1')	

    UPDATE  btype
    SET     nowchange = 0
    IF @@error <> 0 
        GOTO error1	
    UPDATE  Branchbtype
    SET     artotal = 0, aptotal = 0 --where left(typeid,5) not in ('00001','00000')
    IF @@error <> 0 
        GOTO error1	
    UPDATE  Branchbtype
    SET     artotal = 0, aptotal = 0 --where left(typeid,5) ='00001'

----------------------------------------------------------------------------
    IF @@error <> 0 
        GOTO error1	
    TRUNCATE TABLE Billdaynumber
    IF @@error <> 0 
        GOTO error1
    TRUNCATE TABLE Billmonthnumber
    IF @@error <> 0 
        GOTO error1
    TRUNCATE TABLE DlyNdxChecked
    IF @@error <> 0 
        GOTO error1	
    TRUNCATE TABLE DlyChecked
    IF @@error <> 0 
        GOTO error1	
    TRUNCATE TABLE GoodsstockBackup
    IF @@error <> 0 
        GOTO error1	
-- 	truncate table InputLevel   
-- 	if @@error<>0 goto error1
    TRUNCATE TABLE BtypeSupply
    IF @@error <> 0 
        GOTO error1
	
    UPDATE  vchtype
    SET     inputN = 0,
            INputname1 = '',
            INputname2 = '',
            INputname3 = '',
            INputname4 = '',
            INputname5 = ''
    IF @@error <> 0 
        GOTO error1
	
-- 	Delete price From price inner join btype 
-- 		on price.[btypeid]=btype.[typeid] Where btype.[deleted]=1
-- 	if @@error<>0 goto error1		
    DELETE  FROM atype
    WHERE   [deleted] = 1		
    IF @@error <> 0 
        GOTO error1	
	
	
    DELETE  FROM ptype
    WHERE   deleted = 1		
    IF @@error <> 0 
        GOTO error1	
	--商品相关，删除。。。。。。
	delete from ptypecolor where ptypeid not in (select typeid from ptype)
	delete from ptypesize where ptypeid not in (select typeid from ptype)
	delete from PtypeAttribute  where ptypeid not in (select typeid from ptype)
	delete from PtypeBar  where ptypeid not in (select typeid from ptype)
	delete from PTypeGraph  where ptypeid not in (select typeid from ptype)
	delete from PtypePrice	 where ptypeid not in (select typeid from ptype)
	IF @@error <> 0 
        GOTO error1	

    DELETE  FROM btype
    WHERE   [deleted] = 1
            AND TypeId <> '00007'	
    IF @@error <> 0 
        GOTO error1		
	
    DELETE  FROM employee
    WHERE   [deleted] = 1		
    IF @@error <> 0 
        GOTO error1		
	
    DELETE  FROM stock
    WHERE   [deleted] = 1		
    IF @@error <> 0 
        GOTO error1	

    DELETE  FROM department
    WHERE   [deleted] = 1		
    IF @@error <> 0 
        GOTO error1		
	
    DELETE  FROM Branch
    WHERE   [deleted] = 1		
    IF @@error <> 0 
        GOTO error1		


    TRUNCATE TABLE DlyA	   
    IF @@error <> 0 
        GOTO error1	
        
    TRUNCATE TABLE DlyDataDetail   
    IF @@error <> 0 
        GOTO error1
	
    TRUNCATE TABLE DlyData
    IF @@error <> 0 
        GOTO error1
        	
    TRUNCATE TABLE BtypeChange
    IF @@error <> 0 
        GOTO error1		
	
    DELETE  FROM bakdlydetail
    WHERE   dlyorder IN (
            SELECT  dlyorder
            FROM    bakdly
            WHERE   EXISTS ( SELECT vchcode
                             FROM   dlyndx
                             WHERE  draft <> 1
                                    AND bakdly.vchcode = dlyndx.vchcode ) )
    IF @@error <> 0 
        GOTO error1
    DELETE  FROM bakdly
    WHERE   EXISTS ( SELECT vchcode
                     FROM   dlyndx
                     WHERE  draft <> 1
                            AND bakdly.vchcode = dlyndx.vchcode )
    IF @@error <> 0 
        GOTO error1
    DELETE  FROM DlyNdx
    WHERE   [DRAFT] <> 1
    IF @@error <> 0 
        GOTO error1	
	--删除POS生成的草稿
    DELETE  FROM Dlyndx
    WHERE   draft = 0
            OR ISNULL(account, '') = 'COMMONPOSLSJC'
        	
    TRUNCATE TABLE Commission
    IF @@error <> 0 
        GOTO error1	
    TRUNCATE TABLE CommissionDetail
    IF @@error <> 0 
        GOTO error1	
    TRUNCATE TABLE GoodsStocks
    IF @@error <> 0 
        GOTO error1	
    TRUNCATE TABLE GoodsStockDetail  
    IF @@error <> 0 
        GOTO error1
	

    DELETE  FROM MonthProc
    WHERE   period <> 13
    IF @@error <> 0 
        GOTO error1	
    UPDATE  monthproc
    SET     startdate = CONVERT(VARCHAR(4), YEAR(GETDATE())) + '-' + RIGHT('0' + LTRIM(CONVERT(VARCHAR(2), MONTH(GETDATE()))), 2)
            + '-' + RIGHT('0' + LTRIM(CONVERT(VARCHAR(2), DAY(GETDATE()))), 2)
    WHERE   period = 13




    TRUNCATE TABLE Gatheringdly	
    IF @@error <> 0 
        GOTO error1
    UPDATE  atype
    SET     TTl00 = 0, total00 = 0
    WHERE   typeid = '0000500002'
            OR typeid = '00005'
            OR typeid = '0000500001'
    IF @@error <> 0 
        GOTO error1
    TRUNCATE TABLE stockpdstate
    IF @@error <> 0 
        GOTO error1        
---------------------------------------------------------------------系统默认删除已经执行完成的订单
    DELETE  Bakdlyorderdetail
    FROM    Bakdlyorderdetail d,
            BakDlyOrder b,
            DlyNdxOrder o
    WHERE   d.dlyorder = b.dlyorder
            AND b.vchcode = o.vchcode
            AND o.ifcheck = '2'
    IF @@error <> 0 
        GOTO error1

    DELETE  BakDlyOrder
    FROM    BakDlyOrder b,
            DlyNdxOrder o
    WHERE   b.vchcode = o.vchcode
            AND o.ifcheck = '2'
    IF @@error <> 0 
        GOTO error1

    DELETE  FROM DlyNdxOrder
    WHERE   ifcheck = '2'
    IF @@error <> 0 
        GOTO error1

     ---------------------------------------------------------------------清除订单
    IF @ifDD = 'TRUE' 
        BEGIN
            TRUNCATE TABLE  bakdlyorderdetail  
            IF @@error <> 0 
                GOTO error1
		
            TRUNCATE TABLE BakDlyOrder
            IF @@error <> 0 
                GOTO error1
		
            TRUNCATE TABLE DlyNdxOrder
            IF @@error <> 0 
                GOTO error1
			update dlyndx set orderlist ='' --订单都清除完了，订单关联肯定要清完
        END

--------------------------------------------------------------------------------清除过帐标志
    UPDATE  sysdata
    SET     [subvalue] = 0
    WHERE   [subname] = 'iniover'
    IF @@error <> 0 
        GOTO error1		
    UPDATE  branch
    SET     iniover = 0  --所有机构清除开账标志
    IF @@error <> 0 
        GOTO error1		
--------------------------------------------------------------------------------清除盘点准备标志
    UPDATE  sysdata
    SET     [subvalue] = ''
    WHERE   [subname] = 'PdReady'
    IF @@error <> 0 
        GOTO error1		

    UPDATE  sysdata
    SET     [subvalue] = ''
    WHERE   [subname] = 'JMDPdReady'
    IF @@error <> 0 
        GOTO error1		

    UPDATE  sysdata
    SET     [subvalue] = 1
    WHERE   [subname] = 'period'
    IF @@error <> 0 
        GOTO error1	
-----------------------------------------------------------------------恢复记录的最大编号为系统初始状态为零xcy
    UPDATE  sysdata
    SET     [subvalue] = 0
    WHERE   [subname] IN ( 'MaxDlyNdxVchCode', 'MaxDlyNdxOrderVchCode' ) 
    IF @@error <> 0 
        GOTO error1	
----------------------------------------------------------------------清除期初
    IF @Period = 'TRUE' 
        BEGIN
            UPDATE  atype
            SET     [TTL00] = 0,
                    [TTL01] = 0,
                    [TTL02] = 0,
                    [TTL03] = 0,
                    [TTL04] = 0,
                    [TTL05] = 0,
                    [TTL06] = 0,
                    [TTL07] = 0,
                    [TTL08] = 0,
                    [TTL09] = 0,
                    [TTL10] = 0,
                    [TTL11] = 0,
                    [TTL12] = 0,
                    [Total] = 0,
                    [Total00] = 0
            IF @@error <> 0 
                GOTO error1		


            UPDATE  btype
            SET     IniChange = 0,
                    nowchange = 0 
            IF @@error <> 0 
                GOTO error1		
		
            DELETE  FROM Branchbtype
            IF @@error <> 0 
                GOTO error1		
	        
            TRUNCATE TABLE IniGoodsdetail 
            IF @@error <> 0 
                GOTO error1	
		
            TRUNCATE TABLE IniGoodsStocks
            IF @@error <> 0 
                GOTO error1
		

            TRUNCATE TABLE IniCommission
            IF @@error <> 0 
                GOTO error1
		
            TRUNCATE TABLE IniCommissionDetail
            IF @@error <> 0 
                GOTO error1
		
            UPDATE  vipcards
            SET     savemoney = 0 ----  清除VIP储值余额
            IF @@error <> 0 
                GOTO error1
            UPDATE  vipcards
            SET     YearIniMoney = 0 ----  清除VIP储值期初
            IF @@error <> 0 
                GOTO error1
        END
----------------------------------------------------------------------清除当前
    ELSE 
        BEGIN
            UPDATE  atype
            SET     [TTL01] = 0,
                    [TTL02] = 0,
                    [TTL03] = 0,
                    [TTL04] = 0,
                    [TTL05] = 0,
                    [TTL06] = 0,
                    [TTL07] = 0,
                    [TTL08] = 0,
                    [TTL09] = 0,
                    [TTL10] = 0,
                    [TTL11] = 0,
                    [TTL12] = 0,
                    [Total] = 0
            IF @@error <> 0 
                GOTO error1		
            UPDATE  Branchbtype
            SET     [ArTotal] = 0,
                    [ApTotal] = 0
            IF @@error <> 0 
                GOTO error1		
        END


----------------------------------------------------------------------清除已经停用的商品
    IF UPPER(@ifstop) = 'TRUE' 
        BEGIN
            DECLARE @typeid VARCHAR(50),
                @sonnum INT,
                @ifstop1 BIT,
                @parid VARCHAR(50),
                @soncount INT
            DECLARE Ptype_base CURSOR
                FOR SELECT  typeid,
                            stop,
                            parid
                    FROM    ptype
            OPEN Ptype_base
            FETCH NEXT FROM Ptype_base INTO @typeid, @ifstop1, @parid
            WHILE @@FETCH_STATUS = 0
                BEGIN
                    IF @ifstop1 = 1 
                        BEGIN
                            IF NOT EXISTS ( SELECT  *
                                            FROM    inigoodsstocks
                                            WHERE   LEFT(ptypeid, LEN(@typeid)) = @typeid ) 
                                BEGIN 
                                    SELECT  @sonnum = sonnum,
                                            @soncount = soncount
                                    FROM    ptype
                                    WHERE   typeid = @parid
                                    UPDATE  ptype
                                    SET     [sonnum] = @sonnum - 1
                                    WHERE   [typeid] = @parid
                                    IF @@error <> 0 
                                        GOTO error1	
                                END
                        END
                    FETCH NEXT FROM Ptype_base INTO @typeid, @ifstop1, @parid
                END
            CLOSE Ptype_base 
            DEALLOCATE Ptype_base 
            SELECT  Ptypeid
            INTO    #Table
            FROM    ( SELECT    ptypeid
                      FROM      inigoodsstocks
                      WHERE     qty <> 0
                      UNION
                      SELECT    ptypeid
                      FROM      IniCommission
                      WHERE     qty <> 0
                    ) AS c

            DELETE  FROM ptype
            WHERE   typeid NOT IN ( SELECT  LEFT(Ptypeid, LEN(typeid))
                                    FROM    #Table )
                    AND stop = 1
                    AND typeid <> '00000'	
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM ptypebar
            WHERE   ptypeid NOT IN ( SELECT typeid
                                     FROM   ptype )
            IF @@error <> 0 
                GOTO error1	
            DELETE  MultiBarList
            WHERE   ptypeid NOT IN ( SELECT typeid
                                     FROM   ptype )
            IF @@error <> 0 
                GOTO error1	
		
            DELETE  FROM bakdlyorder
            WHERE   ptypeid NOT IN ( SELECT typeid
                                     FROM   ptype
                                     WHERE  sonnum = 0 )
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM BakDLyorderdetail
            WHERE   dlyorder NOT IN ( SELECT    dlyorder
                                      FROM      bakdlyorder )
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM dlyndxorder
            WHERE   vchcode NOT IN ( SELECT vchcode
                                     FROM   bakdlyorder )
            IF @@error <> 0 
                GOTO error1
		
            DELETE  FROM bakdly
            WHERE   ptypeid NOT IN ( SELECT typeid
                                     FROM   ptype
                                     WHERE  sonnum = 0 ) AND ptypeid <> ''
            IF @@error <> 0 
                GOTO error1	
		
            DELETE  FROM bakdlydetail
            WHERE   dlyorder NOT IN ( SELECT    dlyorder
                                      FROM      bakdly )
            IF @@error <> 0 
                GOTO error1
		
            DELETE  FROM dlyndx
            WHERE   vchcode NOT IN ( SELECT DISTINCT
                                            vchcode
                                     FROM   bakdly
                                     UNION
                                     SELECT DISTINCT
                                            vchcode
                                     FROM   DlyData )
            IF @@error <> 0 
                GOTO error1
		
            ( SELECT    od.dlyorder
              FROM      Bakdlyorderdetail od
              WHERE     od.qty > od.toqty
            ) 
	
            IF @@error <> 0
                OR @@ROWCOUNT < 0 
                GOTO error1
	
            UPDATE  dlyndxorder
            SET     [ifcheck] = '0',
                    [Isover] = 0
            FROM    dlyndxorder a
            WHERE   EXISTS ( SELECT 1
                             FROM   bakdlyorder b
                             WHERE  a.vchcode = b.vchcode
                                    AND ISNULL(isover, 0) = 0 ) 
		    
            IF @@error <> 0
                OR @@ROWCOUNT < 0 
                RETURN -1	
            UPDATE  dlyndxorder
            SET     [ifcheck] = '2',
                    [Isover] = 1
            FROM    dlyndxorder a
            WHERE   NOT EXISTS ( SELECT 1
                                 FROM   bakdlyorder b
                                 WHERE  a.vchcode = b.vchcode
                                        AND ISNULL(isover, 0) = 0 ) 
            IF @@error <> 0
                OR @@ROWCOUNT < 0 
                GOTO error1
	
        END
---------------------------------------------------------------------------------
---------------------------------------------------------------------清除草稿
    IF @BakDly = 'TRUE' 
        BEGIN
            TRUNCATE TABLE DZTVchcode
            IF @@error <> 0 
                GOTO error1

            TRUNCATE TABLE DlyNdx
            IF @@error <> 0 
                GOTO error1	
		
            TRUNCATE TABLE BakDlyDetail
            IF @@error <> 0 
                GOTO error1	
		
            TRUNCATE TABLE BakDly
            IF @@error <> 0 
                GOTO error1		
		
        END
    ELSE 
        BEGIN
            DELETE  bakdlydetail
            WHERE   dlyorder IN (
                    SELECT  dlyorder
                    FROM    bakdly
                    WHERE   vchcode IN ( SELECT vchcode
                                         FROM   dlyndx
                                         WHERE  vchtype IN ( 9, 14, 140, 141 )
                                                AND ISNULL(expandid, '') <> '' ) )
            DELETE  bakdly
            WHERE   vchcode IN ( SELECT vchcode
                                 FROM   dlyndx
                                 WHERE  vchtype IN ( 9, 14, 140, 141)
                                        AND ISNULL(expandid, '') <> '' )
            DELETE  dlyndx
            WHERE   vchtype IN ( 9, 14, 140, 141)
					AND ISNULL(expandid, '') <> '' 
        END


--0023010: 系统重建：需求确认，不论是否选择清除草稿，都要配货验收里的验收单草稿清除
--：还要删除收付款单和往来核销单据的草稿
    DELETE  bakdlydetail
    WHERE   dlyorder IN (
            SELECT  dlyorder
            FROM    bakdly
            WHERE   vchcode IN ( SELECT vchcode
                                 FROM   dlyndx
                                 WHERE  draft = 1
                                        AND vchtype IN ( 232, 224 ) ) )
    DELETE  bakdly
    WHERE   vchcode IN ( SELECT vchcode
                         FROM   dlyndx
                         WHERE  draft = 1
                                AND vchtype IN ( 232, 224 , 4, 66) )
    DELETE  dlyndx
    WHERE   draft = 1
            AND vchtype IN ( 232, 224, 4 , 66 , 253 ) 


--------------------------------------------------------------------清除基本信息
    IF @BasicInf = 'TRUE' 
        BEGIN
	    TRUNCATE TABLE   PHGroupDetail
	    TRUNCATE TABLE   PHGroupMain
 	     
 	    Truncate table DZTConfig
	    IF @@error <> 0 
	        GOTO error1 
 	    
            Truncate table PTypeGraph
	    IF @@error <> 0 
	        GOTO error1
	        
            DELETE  FROM CommonPosInfo
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM ChangeGoodsSetting
            WHERE   BTypeID <> ''
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM branch
            WHERE   branchid NOT IN ( '00000', '00001', '00004', '0000100001' )-- comment<>'系统默认'
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE ptypeattribute
            IF @@error <> 0 
                GOTO error1
            TRUNCATE TABLE AssistAttribute
            IF @@error <> 0 
                GOTO error1
            TRUNCATE TABLE AssistType
            IF @@error <> 0 
                GOTO error1
            DELETE  FROM ptype
            WHERE   typeid <> '00000'  
            IF @@error <> 0 
                GOTO error1	

            DELETE  FROM SalabilityPtype 
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM btype
            WHERE   typeid <> '00000'
                    AND typeid NOT IN ( '0000100001', '0000200001',
                                        '0000300001', '0000500001',
                                        '0000600001', '00001', '00002',
                                        '00003', '00004', '00005', '00006',
                                        '00007' )
            DELETE  FROM btype
            WHERE   typeid NOT IN ( '00000' )
                    AND typeid NOT IN ( '0000100001', '0000200001',
                                        '0000300001', '0000500001',
                                        '0000600001', '00001', '00002',
                                        '00003', '00004', '00005', '00006',
                                        '00007' )
                    AND branchid NOT IN ( SELECT    branchid
                                          FROM      branch )
            UPDATE  btype
            SET     sonnum = 1, soncount = 1
            WHERE   leveal = 1
                    AND typeid <> '00006'
            UPDATE  btype
            SET     sonnum = 0, soncount = 0
            WHERE   leveal = 1
                    AND typeid = '00006'
            UPDATE  btype
            SET     sonnum = 0, soncount = 0
            WHERE   leveal = 2
            UPDATE  btype
            SET     sonnum = 7, soncount = 7
            WHERE   leveal = 0
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM atype
            WHERE   sysrow = 0
                    AND typeid <> '000010000400001'	
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM atype
            WHERE   branchid NOT IN ( SELECT    branchid
                                      FROM      branch )
	                   
            DELETE  FROM loginuser
            WHERE   etypeid <> '00000'  
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM employee
            WHERE   typeid <> '00000'  
            DELETE  FROM employee
            WHERE   typeid NOT IN ( '00000' )
                    AND branchid NOT IN ( SELECT    branchid
                                          FROM      branch )
            TRUNCATE TABLE employeepower  --清除权限表数据
            DELETE  FROM userpowerrange
            WHERE   etypeid <> '00000'   --清空除超级用户外的权限范围
            TRUNCATE TABLE RetailSetup    --清空零售配置
            TRUNCATE TABLE RetailAtype    --清空零售收银配置

			  --清除相关审核流程
            TRUNCATE TABLE   AuditingFlowSet --审核主表
            TRUNCATE TABLE   AuditingFlowDetail --审核过程记录表
            TRUNCATE TABLE   AuditingStepReason --存放审核步骤具体值的表
            TRUNCATE TABLE   AuditingReason --审核原因选择表



            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM stock
            WHERE   typeid <> '00000'
                    AND typeid NOT IN ( '0000100001', '00001', '00003',
                                        '00007', '99999', '00004' )
            DELETE  FROM stock
            WHERE   typeid NOT IN ( '00000', '00001', '99999' )
                    AND branchid NOT IN ( SELECT    branchid
                                          FROM      branch )
				

            UPDATE  stock
            SET     sonnum = 1, soncount = 1
            WHERE   leveal = 1
            UPDATE  stock
            SET     sonnum = 0, soncount = 0
            WHERE   leveal = 2
            UPDATE  stock
            SET     sonnum = 4, soncount = 4
            WHERE   leveal = 0
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM ColorGrouprelation
            WHERE   colorgroupid <> 1   
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM ColorGroup
            WHERE   colorgroupid <> 1  
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM Color
            WHERE   sysrow = 0
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM SizeGrouprelation
            WHERE   sizeid IN ( SELECT  sizeid
                                FROM    [size]
                                WHERE   sysrow = 0 )
                    AND SizeGroupid IN ( SELECT SizeGroupid
                                         FROM   SizeGroup
                                         WHERE  sysrow = 0 )   
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM SizeGroup
            WHERE   sysrow = 0
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM [size]
            WHERE   sysrow = 0
            IF @@error <> 0 
                GOTO error1	
-- 	          delete from price
-- 	          if @@error<>0 goto error1	
            DELETE  FROM ptypebar  
            IF @@error <> 0 
                GOTO error1	

            DELETE  FROM MultiBarList  
            IF @@error <> 0 
                GOTO error1	

            DELETE  PtypeBarType
            WHERE   bartypeid <> 1
            IF @@error <> 0 
                GOTO error1	
	         
            DELETE  FROM department
            WHERE   typeid <> '00000'  
            IF @@error <> 0 
                GOTO error1	

            DELETE  FROM department
            WHERE   typeid NOT IN ( '00000' )
                    AND branchid NOT IN ( SELECT    branchid
                                          FROM      branch )
	        
            DELETE  FROM AssistAttribute
            IF @@error <> 0 
                GOTO error1	
	     
            TRUNCATE TABLE  BtypeChange
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE PMmain
            IF @@error <> 0 
                GOTO error1
	
            TRUNCATE TABLE pMdetail
            IF @@error <> 0 
                GOTO error1
            TRUNCATE TABLE  Site
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE  POS
            IF @@error <> 0 
                GOTO error1	
	
            TRUNCATE TABLE site--	清除门店设置表
            IF @@error <> 0 
                GOTO error1
		--清除订单	  
            TRUNCATE TABLE BakDlyOrderdetail  
            IF @@error <> 0 
                GOTO error1
		
            TRUNCATE TABLE BakDlyOrder
            IF @@error <> 0 
                GOTO error1
		
            TRUNCATE TABLE DlyNdxOrder
            IF @@error <> 0 
                GOTO error1
		 --清除促销
            TRUNCATE TABLE DlySalePromNo1
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo2
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo3
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo4
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo5
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo6
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo7
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo8
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo_zhdetail
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo_zhMain
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlyNdxSale_CXD
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySaleP_CXD
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySaleB_CXD
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySaleProm
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlyNdxProm
            IF @@error <> 0 
                GOTO error1
            TRUNCATE TABLE DlySaleBtype
            IF @@error <> 0 
                GOTO error1
		--清除草稿
            TRUNCATE TABLE DlyNdx
            IF @@error <> 0 
                GOTO error1	
		
            TRUNCATE TABLE BakDlyDetail
            IF @@error <> 0 
                GOTO error1	
		
            TRUNCATE TABLE BakDly
            IF @@error <> 0 
                GOTO error1		
			--清除期初
            UPDATE  atype
            SET     [TTL00] = 0,
                    [TTL01] = 0,
                    [TTL02] = 0,
                    [TTL03] = 0,
                    [TTL04] = 0,
                    [TTL05] = 0,
                    [TTL06] = 0,
                    [TTL07] = 0,
                    [TTL08] = 0,
                    [TTL09] = 0,
                    [TTL10] = 0,
                    [TTL11] = 0,
                    [TTL12] = 0,
                    [Total] = 0,
                    [Total00] = 0
            IF @@error <> 0 
                GOTO error1		
		
            UPDATE  btype
            SET     IniChange = 0,
                    nowchange = 0 
            IF @@error <> 0 
                GOTO error1		

            UPDATE  Branchbtype
            SET     [ArTotal00] = 0,
                    [ApTotal00] = 0,
                    [ArTotal] = 0,
                    [ApTotal] = 0
            IF @@error <> 0 
                GOTO error1		
	        
            TRUNCATE TABLE IniGoodsdetail 
            IF @@error <> 0 
                GOTO error1	
		
            TRUNCATE TABLE IniGoodsStocks
            IF @@error <> 0 
                GOTO error1
		
			
            TRUNCATE TABLE IniCommission
            IF @@error <> 0 
                GOTO error1
		
            TRUNCATE TABLE IniCommissionDetail
            IF @@error <> 0 
                GOTO error1
		
		--清除单据的审核设置
            IF EXISTS ( SELECT  1
                        FROM    BusinessFlow ) 
                UPDATE  BusinessFlow
                SET     inputn = 0,
                        inputname1 = '',
                        inputname2 = '',
                        inputname3 = '',
                        inputname4 = '',
                        inputname5 = ''
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE InputLevel
            IF @@error <> 0 
                GOTO error1	
		--清除门店零售配置
            TRUNCATE TABLE dbo.PtypePrice
            IF @@error <> 0 
                GOTO error1	

            UPDATE  dbo.xw_BaseUpdateTag
            SET     UpdateTag = 0
            IF @@error <> 0 
                GOTO error1	

		
        END
----------------------------------------------------------------------------------------		
   
    IF @ifvip = 'TRUE'-------------------清除Vip
        BEGIN
            TRUNCATE TABLE VIPCards
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE VIPCardTypes
            IF @@error <> 0 
                GOTO error1	
			TRUNCATE TABLE  VipFillMoneyRule	
			TRUNCATE TABLE  VipPtypeRule                         
            TRUNCATE TABLE   VipCardIntegralTransact          
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE   VIPCardIntegralSend          
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE   VIPCardExpand       
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE   VIPCardBound    
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE   vipintegraldetail    
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE VIPCards   
            IF @@error <> 0 
                GOTO error1
            SELECT  *
            INTO    #Atype
            FROM    Atype
            UPDATE  atype
            SET     ttl00 = ( SELECT    ttl00
                              FROM      #Atype
                              WHERE     typeid = '0000299999'
                                        AND branchid = atype.branchid
                            )
            WHERE   typeid = '0000500001'
            DROP TABLE #Atype
            IF @@error <> 0 
                GOTO error1
            UPDATE  atype
            SET     ttl00 = 0
            WHERE   typeid = '0000299999'
            IF @@error <> 0 
                GOTO error1

            UPDATE  dlyndx
            SET     vipcardid = 0
            UPDATE  bakdly
            SET     vipcardid = 0
            DELETE  FROM bakdly
            WHERE   atypeid = '0000299999' --删除VIP储值支付
        END
------------------------------------------------------------------------------------------
    IF @CX = 'TRUE'--清除促销设置
        BEGIN
            TRUNCATE TABLE DlySalePromNo1
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo2
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo3
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo4
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo5
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo6
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo7
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo8
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo_zhdetail
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySalePromNo_zhMain
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlyNdxSale_CXD
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySaleP_CXD
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySaleB_CXD
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlySaleProm
            IF @@error <> 0 
                GOTO error1	
            TRUNCATE TABLE DlyNdxProm
            IF @@error <> 0 
                GOTO error1
            TRUNCATE TABLE DlySaleBtype
            IF @@error <> 0 
                GOTO error1
        END

	--清除零售计划设置相关        
	truncate table SalePlanBill
	truncate table SalePlanConfig
	truncate table SalePlanBillDetail

--最后再清一个主表不在的单据明细
    DELETE  FROM bakdly
    WHERE   NOT EXISTS ( SELECT vchcode
                         FROM   dlyndx
                         WHERE  bakdly.vchcode = dlyndx.vchcode )
    IF @@error <> 0 
        GOTO error1
    DELETE  FROM bakdlydetail
    WHERE   dlyorder NOT IN ( SELECT    dlyorder
                              FROM      bakdly )
    IF @@error <> 0 
        GOTO error1


  /***************************************
系统重建和年结存 关于 清除审核的相关操作
***************************************/
--1.
    DELETE  FROM AuditingFlowSet
    WHERE   IfUse = 0 --审核主表(删除已经过期的审核流程)
--2.
    DELETE  FROM AuditingBill --审核记录表(存放单据审核的最终审核状态和审核的历史记录）
--3.(如果有保留 未完成的订单 配置)
    UPDATE  DlyNdxOrder
    SET     IfAudit = 2
    WHERE   IfAudit = 1 --审核通过的订单--》改成 无需审核的订单
    UPDATE  DlyNdxOrder
    SET     IfAudit = -2
    WHERE   IfAudit IN ( 0, -1 ) --待审核和审核不通过的订单--》改成 满足审核不提交




-------------------- 清除上下传用表
    IF EXISTS ( SELECT  1
                FROM    sysobjects
                WHERE   id = OBJECT_ID('dbo.transbill')
                        AND type = 'U' ) 
        BEGIN
        
	--if exists(Select 1 From sysdata where subname='mendatabase' and subvalue='')
	--Begin
            TRUNCATE TABLE transbill
            IF @@error <> 0 
                GOTO error1
            TRUNCATE TABLE transbilldetail
            IF @@error <> 0 
                GOTO error1
            TRUNCATE TABLE  AdjustTrack
            IF @@error <> 0 
                GOTO error1
       
        --强制要求所有门店重建
            UPDATE  site
            SET     startupAccount = 0 
            IF @@error <> 0 
                GOTO error1


--         -- 强制回复系统配置状态的一致性，以保证独立门店那边的一致性
--     	update syscon set [stats]=1 where [order] in (106,108,14)
--     	if @@error<>0 goto error1
	
        --清空上下传设计的临时表
	  
            EXEC @ret= FZClearTempTable
            IF @ret < 0 
                GOTO error1

  -------------------- 清除未过帐单据
        -- 未正常过帐的事务强制忽略掉
            UPDATE  Synctrans
            SET     TransErrorNo = 101
            WHERE   TransErrorNo < 0

            TRUNCATE TABLE TransErrorBillNdx
            IF @@error <> 0 
                GOTO error1
            TRUNCATE TABLE TransErrorBill
            IF @@error <> 0 
                GOTO error1
            TRUNCATE TABLE TransErrorBillDetaiL
            IF @@error <> 0 
                GOTO error1       


	--end
        END
--------------------

    UPDATE  sysdata
    SET     subvalue = CONVERT(VARCHAR(4), YEAR(GETDATE())) + '-' + RIGHT('0' + LTRIM(CONVERT(VARCHAR(2), MONTH(GETDATE()))), 2)
            + '-' + RIGHT('0' + LTRIM(CONVERT(VARCHAR(2), DAY(GETDATE()))), 2)
    WHERE   subname = 'startdate'
    UPDATE  sysdata
    SET     subvalue = CONVERT(VARCHAR(4), YEAR(GETDATE())) + '-' + RIGHT('0' + LTRIM(CONVERT(VARCHAR(2), MONTH(GETDATE()))), 2)
            + '-' + RIGHT('0' + LTRIM(CONVERT(VARCHAR(2), DAY(GETDATE()))), 2)
    WHERE   subname = 'enddate'       

-- 重算基本信息表中的sonnum 和soncount
    EXEC [dbo].[XW_GetUpdateTag] 'ptype', @UpdateTag OUTPUT		
    UPDATE  ptype
    SET     updatetag = @updateTag,
            SonNum = ISNULL(( SELECT    COUNT(Typeid)
                              FROM      ptype
                              WHERE     a.typeid = Parid
                                        AND deleted = 0
                            ), 0)
    FROM    ptype a

    UPDATE  ptype
    SET     updatetag = @updateTag,
            SonCount = ISNULL(( SELECT  CAST(MAX(RIGHT(typeid, 5)) AS INT)
                                FROM    ptype
                                WHERE   a.typeid = Parid
                                        --AND deleted = 0
                              ), 0)
    FROM    ptype a

    EXEC [dbo].[XW_GetUpdateTag] 'btype', @UpdateTag OUTPUT		
    UPDATE  btype
    SET     updatetag = @updateTag,
            SonNum = ISNULL(( SELECT    COUNT(Typeid)
                              FROM      btype
                              WHERE     a.typeid = Parid
                                        AND deleted = 0
                            ), 0)
    FROM    btype a

    UPDATE  btype
    SET     updatetag = @updateTag,
            SonCount = ISNULL(( SELECT  CAST(MAX(RIGHT(typeid, 5)) AS INT)
                                FROM    btype
                                WHERE   a.typeid = Parid
                                       -- AND deleted = 0
                              ), 0)
    FROM    btype a

    EXEC [dbo].[XW_GetUpdateTag] 'Stock', @UpdateTag OUTPUT		
    UPDATE  Stock
    SET     updatetag = @updateTag,
            SonNum = ISNULL(( SELECT    COUNT(Typeid)
                              FROM      Stock
                              WHERE     a.typeid = Parid
                                        AND deleted = 0
                            ), 0)
    FROM    Stock a

    UPDATE  Stock
    SET     updatetag = @updateTag,
            SonCount = ISNULL(( SELECT  CAST(MAX(RIGHT(typeid, 5)) AS INT)
                                FROM    Stock
                                WHERE   a.typeid = Parid
                                        --AND deleted = 0
                              ), 0)
    FROM    Stock a


    EXEC [dbo].[XW_GetUpdateTag] 'atype', @UpdateTag OUTPUT		

    UPDATE  atype
    SET     updatetag = @updateTag,
            SonNum = ISNULL(( SELECT    COUNT(Typeid)
                              FROM      atype
                              WHERE     branchid = a.branchid
                                        AND a.typeid = Parid
                                        AND deleted = 0
                            ), 0)
    FROM    atype a


    UPDATE  atype
    SET     updatetag = @updateTag,
            SonCount = ISNULL(( SELECT  CAST(MAX(RIGHT(typeid, 5)) AS INT)
                                FROM    atype
                                WHERE   branchid = a.branchid
                                        AND a.typeid = Parid
                                       -- AND deleted = 0
                              ), 0)
    FROM    atype a

--所有加盟机构的资产科目SonCount+1,因为内部结算科目只有加盟商没有，重算时如果按照儿子数算，新增科目ID会是 ‘0000100009’，而这个ID代表的是内部结算科目
    UPDATE  atype
    SET     SonCount = SonCount + 1
    WHERE   LEFT(branchid, 5) = '00004'
            AND typeid = '00001'
            AND Soncount < 9

    EXEC [dbo].[XW_GetUpdateTag] 'employee', @UpdateTag OUTPUT	
    UPDATE  employee
    SET     updatetag = @updateTag,
            SonNum = ISNULL(( SELECT    COUNT(Typeid)
                              FROM      employee
                              WHERE     a.typeid = Parid
                                        AND deleted = 0
                            ), 0)
    FROM    employee a

    UPDATE  employee
    SET     updatetag = @updateTag,
            SonCount = ISNULL(( SELECT  CAST(MAX(RIGHT(typeid, 5)) AS INT)
                                FROM    employee
                                WHERE   a.typeid = Parid
                                       -- AND deleted = 0
                              ), 0)
    FROM    employee a

    EXEC [dbo].[XW_GetUpdateTag] 'department', @UpdateTag OUTPUT	
    UPDATE  department
    SET     updatetag = @updateTag,
            SonNum = ISNULL(( SELECT    COUNT(Typeid)
                              FROM      department
                              WHERE     a.typeid = Parid
                                        AND deleted = 0
                            ), 0)
    FROM    department a

    UPDATE  department
    SET     updatetag = @updateTag,
            SonCount = ISNULL(( SELECT  CAST(MAX(RIGHT(typeid, 5)) AS INT)
                                FROM    department
                                WHERE   a.typeid = Parid
                                        --AND deleted = 0
                              ), 0)
    FROM    department a

    EXEC [dbo].[XW_GetUpdateTag] 'Branch', @UpdateTag OUTPUT		
    UPDATE  Branch
    SET     updatetag = @updateTag,
            SonNum = ISNULL(( SELECT    COUNT(Branchid)
                              FROM      Branch
                              WHERE     a.Branchid = Parid
                                        AND deleted = 0
                            ), 0)
    FROM    Branch a

    UPDATE  Branch
    SET     updatetag = @updateTag,
            SonCount = ISNULL(( SELECT  CAST(MAX(RIGHT(Branchid, 5)) AS INT)
                                FROM    Branch
                                WHERE   a.Branchid = Parid
                                        --AND deleted = 0
                              ), 0)
    FROM    Branch a

    EXEC [dbo].[XW_GetUpdateTag] 'VipCards', @UpdateTag OUTPUT	
    UPDATE  VipCards
    SET     updatetag = @updateTag


    EXEC [dbo].[XW_GetUpdateTag] 'COLOR', @UpdateTag OUTPUT	
    UPDATE  COLOR
    SET     updatetag = @updateTag

    EXEC [dbo].[XW_GetUpdateTag] 'SIZE', @UpdateTag OUTPUT	
    UPDATE  SIZE
    SET     updatetag = @updateTag




-- 清空虚拟库存
    
    TRUNCATE TABLE GoodsVirtual
    IF @@error <> 0 
        GOTO error1       
    --add by hww 处理单据编号重复的问题，暂时不确定BS也需要，故只针对CS执行
    IF EXISTS(SELECT * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZCS')
    EXEC FZInitBillNumber
	
	--删除没有主表的dlyNdxB DlyNdxOrderB记录
	delete from dlyNdxB where not exists (select 1 from dlyndx d where d.vchcode=vchcode)
	delete from DlyNdxOrderB where not exists (select 1 from DlyNdxOrder d where d.vchcode=vchcode)
	
	--POS更新标识
	TRUNCATE TABLE SystemRebuildGuid
	INSERT  INTO SystemRebuildGuid
        SELECT  NEWID()
	
    COMMIT TRAN DELBILL
    GOTO succee

    succee:    
    RETURN 0	
    error1:
    ROLLBACK TRAN DELBILL
    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].[FZYearClose_BS]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZYearClose_BS]
GO




--  ********************************************************************************************
--  ||                                                                                        
--  ||   过程名称：FZYearClose_BS                                     
--  ||   过程功能：年结存
--  ||=========================================================================================
--  ||   参数说明：  参数名称         类型            意义                     输入输出
--  ||            -----------------------------------------------------------------------------
--  ||          
--  ||=========================================================================================   
--  ||   返回值：         值                                     说明
--  ||       ----------------------------------------------------------------------------------------
--  ||                    0                                 执行成功
--  ||                  －1                               执行失败
--  ||==========================================================================================

/*
作者：cqhua
日期：2011-08-18
修改原因：清除商品积分明细 VipIntegralPtypeDetail
*/

CREATE PROCEDURE FZYearClose_BS
    (
      @ifdelptype BIT = 0,
      @ifdelvip BIT = 0,
      @ifForeExec BIT = 0,
      @branchid VARCHAR(50) = ''
    )
AS 
    DECLARE @SQL VARCHAR(500)
    DECLARE @szTemp VARCHAR(20)
    DECLARE @nInit SMALLINT
    DECLARE @nvchcode INT
    DECLARE @oDlyOrder INT
    DECLARE @nDlyOrder INT


    DECLARE @Today DATETIME

    SELECT  @Today = CONVERT(DATETIME, CONVERT(VARCHAR(4), YEAR(GETDATE()))
            + '-' + RIGHT('0' + LTRIM(CONVERT(VARCHAR(2), MONTH(GETDATE()))),
                          2) + '-' + RIGHT('0'
                                           + LTRIM(CONVERT(VARCHAR(2), DAY(GETDATE()))),
                                           2))
---------------------------------



    IF @ifForeExec = 0
        AND @branchid = '' --总部年结才检查
        BEGIN
            SELECT  @nInit = subvalue
            FROM    sysdata
            WHERE   subname = 'iniover'
            IF @nInit = 0 
                RETURN -2

		--年结存时控制：只要有同价/变价配货单未验收，不能年结存，其余不控制 
            IF EXISTS ( SELECT  *
                        FROM    dlyndx
                        WHERE   draft IN ( 4, 6 ) ) 
                RETURN -30--还有单据没有验收  -- vchtype in (212,218) and 
            IF EXISTS ( SELECT  *
                        FROM    dlyndx
                        WHERE   draft = 1
                                AND vchtype = 230 ) 
                RETURN -30  --配货差额调整单

		--if exists(Select * from dlyndx where  draft=10) return -31 --还有零售单没有结算
		--if exists(Select * from POSRetailBill where draft =0) return -31
        END
    IF @branchid <> '' --加盟还未开账
        BEGIN
            IF EXISTS ( SELECT  1
                        FROM    branch
                        WHERE   branchid = @branchid
                                AND iniover = 0 ) 
                RETURN -2
        END
    BEGIN TRAN YearClose

    --清除电帐通表
    
    TRUNCATE TABLE dbo.DZTVchcode
    --订货会日志表
    TRUNCATE TABLE dbo.MpoImport

	--清全能进销存作业表
	TRUNCATE TABLE TableForAllJXC
	Update QueryVchcodeRec set subvalue = '0' where subname = 'AllPowerMaxVch'
	
	--清空库龄分析作业表
	TRUNCATE TABLE dbo.StockAgeDetail
	
    TRUNCATE TABLE GoodsstockBackupRecord

	--临时记录表中的记录倒入查询表中
 
-- 	delete from price where ptypeid in (Select typeid from ptype where deleted=1)
--      	if @@Error<>0 goto error1
-- 
-- 	delete from price where btypeId in (Select typeid from btype where deleted=1)
--      	if @@Error<>0 goto error1
-- 	

             

--             declare  @bdate  varchar(50)  ,@edate  varchar(50)
--             select  @bdate=min([date]),@edate=max([date])  from  dlyndx   
--             select  @bdate=@bdate+'至'+@edate 
--             insert into salehis 
--            select  @bdate, ss.usercode,ss.fullname, ss.sy ,ss.sm ,sum(ss.qty) as qty ,sum(ss.tax_total) as taxtotal
--             from
--             (  select p.usercode,p.fullname, left(s.date,4) as sy ,left(s.date,7) as sm ,s.qty ,s.tax_total
--               from ptype p , dlydata  s 
--               where p.typeid=s.ptypeid  and s. vchtype in (11,45,26,24,222,12,13,224) 
--             ) ss
--             group by  ss.usercode,ss.fullname,ss.sy,ss.sm  

    IF @branchid = '' 
        BEGIN
            DELETE  FROM atype
            WHERE   [deleted] = 1		
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM ptype
            WHERE   [deleted] = 1		
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM btype
            WHERE   [deleted] = 1		
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM employee
            WHERE   [deleted] = 1		
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM stock
            WHERE   [deleted] = 1		
            IF @@Error <> 0 
                GOTO error1
        END


    IF @branchid = '' 
        BEGIN
		----清除智能配货相关
		delete from AutoPhTitleData where MainBranchid IN ( SELECT branchid FROM branch WHERE     selfiniyear = 0 )
		delete from AutoPhOrderTitleData  where MainBranchid IN ( SELECT branchid FROM branch WHERE     selfiniyear = 0 )
		delete from AutoPhGrdData where etypeid not in (select etypeid from AutoPhTitleData)
		delete from AutoPhOrderGrdData  where etypeid not in (select etypeid from AutoPhOrderTitleData)
		--清除退货调整单(过期的）
		delete from ChangeBillNdx  where btypeid in ( select btypeid from btype where branchid in ( SELECT branchid FROM branch WHERE     selfiniyear = 0 )) AND
		dateadd(d,effectiveDays,billdate)<Convert(datetime,convert(varchar(10),year(getdate()))+'-'+right('0'+convert(varchar(10),month(getdate())),2)+'-'+right('0'+convert(varchar(10),day(getdate())),2))
		delete from ChangeBillData where billcode not in (select billcode from ChangeBillNdx)
		delete from  btyperetqty 
		where outdate<getdate() 
		and btypeid in ( select btypeid from btype where branchid in ( SELECT branchid FROM branch WHERE     selfiniyear = 0 ))
		AND (Vchtype<>0 OR (Vchtype =0 AND VchCode NOT IN (select VchCode from ChangeBillNdx)))
		delete from  btyperettotal where outdate<getdate()  
		and btypeid in ( select btypeid from btype where branchid in ( SELECT branchid FROM branch WHERE     selfiniyear = 0 ))
		AND (Vchtype<>0 OR (Vchtype =0 AND VchCode NOT IN (select VchCode from ChangeBillNdx)))


		--------清除POS小票及促销-------- (POS小票要已经结存的才删除）
		--  清除新POS4.1相关
            DELETE  dbo.tpx_SaleIndex
            WHERE   JTypeId IN ( SELECT    branchid
                                  FROM      branch
                                  WHERE     selfiniyear = 0 )
                    AND draftVchcode <> 0
                     
            DELETE  dbo.tpx_SaleList
            WHERE   ZBKeyId NOT IN ( SELECT  keyId
                                        FROM    dbo.tpx_SaleIndex )
            DELETE  dbo.tpx_SaleVipList
            WHERE   ZBKeyId NOT IN ( SELECT  keyId
                                        FROM    dbo.tpx_SaleIndex )
            DELETE dbo.tpx_SalePayList
            WHERE ZBKeyId NOT IN(SELECT KeyId FROM dbo.tpx_SaleIndex)
            
            DELETE dbo.tpx_SaleManList
            WHERE CBKeyId NOT IN (SELECT KeyId FROM dbo.tpx_SaleList)   
            
                                     
			
		--删除POS结存(PDVchCode<>0表明已生成后台盘点单）
            DELETE  FROM dbo.tpx_CheckNdx
            WHERE   ktypeid IN (
                    SELECT  typeid
                    FROM    stock
                    WHERE   branchid IN ( SELECT    branchid
                                          FROM      branch
                                          WHERE     selfiniyear = 0 ) )
                    AND PDVchCode <> 0
            DELETE  FROM dbo.tpx_CheckList
            WHERE   ZBkeyid NOT IN ( SELECT   keyid
                                      FROM     dbo.tpx_CheckNdx )
    
			DELETE dbo.tpx_CheckPointNdx WHERE Audit=1
			TRUNCATE TABLE dbo.tpx_BillMaxNo
			TRUNCATE TABLE dbo.tpx_BillNoPool

		-- 先删除适用范围 -- 机构(非单独年结的机构)，再把无适用范围的其它相关表删除
            DELETE  dbo.tpx_CXBillBound
            WHERE   ktypeid IN ( SELECT branchid
                                 FROM   branch
                                 WHERE  selfiniyear = 0 )
                    AND EXISTS ( SELECT 1
                                 FROM   dbo.tpx_CXBillIndex
                                 WHERE  tpx_CXBillIndex.BILLNUMBERID = dbo.tpx_CXBillBound.BILLNUMBERID
                                        AND @Today > ENDDATE )
            DELETE  dbo.tpx_CXBillIndex
            WHERE   @Today > ENDDATE
                    AND billnumberid NOT IN ( SELECT    billnumberid
                                              FROM      dbo.tpx_CXBillBound ) 		
            DELETE  dbo.tpx_CXBillComD
            WHERE   billnumberid NOT IN ( SELECT    billnumberid
                                          FROM      dbo.tpx_CXBillIndex )
            DELETE  dbo.tpx_CXBillCom
            WHERE   billnumberid NOT IN ( SELECT    billnumberid
                                          FROM      dbo.tpx_CXBillIndex )
            DELETE  dbo.tpx_CXBillLarg
            WHERE   billnumberid NOT IN ( SELECT    billnumberid
                                          FROM      dbo.tpx_CXBillIndex )
            DELETE  dbo.tpx_CXBillHand
            WHERE   billnumberid NOT IN ( SELECT    billnumberid
                                          FROM      dbo.tpx_CXBillIndex )
            DELETE  dbo.tpx_CXBillSpec
            WHERE   billnumberid NOT IN ( SELECT    billnumberid
                                          FROM      dbo.tpx_CXBillIndex )


            DELETE  FROM DlyData
            WHERE   branchid IN ( SELECT    branchid
                                  FROM      branch
                                  WHERE     selfiniyear = 0 )
                    OR ktypeid = '99999' --在途库
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM Dlya
            WHERE   branchid IN ( SELECT    branchid
                                  FROM      branch
                                  WHERE     selfiniyear = 0 )
            IF @@Error <> 0 
                GOTO error1
	
            DELETE  FROM DlyDataDetail
            WHERE   dlyorder NOT IN ( SELECT    dlyorder
                                      FROM      DlyData )
            IF @@Error <> 0 
                GOTO error1
	
		
            DELETE  FROM bakdly
            WHERE   EXISTS ( SELECT vchcode
                             FROM   dlyndx
                             WHERE  draft NOT IN ( 1, 9 )
                                    AND bakdly.vchcode = dlyndx.vchcode
                                    AND ( ( vchtype NOT IN ( 222, 224, 232,
                                                             234 )
                                            AND ( branchid IN (
                                                  SELECT    branchid
                                                  FROM      branch
                                                  WHERE     selfiniyear = 0 )
                                                  OR branchid2 IN (
                                                  SELECT    branchid
                                                  FROM      branch
                                                  WHERE     selfiniyear = 0 )
                                                )
                                          )
                                          OR ( vchtype IN ( 232, 224 )
                                               AND branchid IN (
                                               SELECT   branchid
                                               FROM     branch
                                               WHERE    selfiniyear = 0 )
                                             )
                                          OR ( vchtype IN ( 222, 234 )
                                               AND branchid2 IN (
                                               SELECT   branchid
                                               FROM     branch
                                               WHERE    selfiniyear = 0 )
                                             )
                                        ) )

            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM DlyNdx
            WHERE   draft NOT IN ( 1, 9 )
                    AND ( ( vchtype NOT IN ( 222, 224, 232, 234 )
                            AND ( branchid IN ( SELECT  branchid
                                                FROM    branch
                                                WHERE   selfiniyear = 0 )
                                  OR branchid2 IN ( SELECT  branchid
                                                    FROM    branch
                                                    WHERE   selfiniyear = 0 )
                                )
                          )
                          OR ( vchtype IN ( 232, 224 )
                               AND branchid IN ( SELECT branchid
                                                 FROM   branch
                                                 WHERE  selfiniyear = 0 )
                             )
                          OR ( vchtype IN ( 222, 234 )
                               AND branchid2 IN ( SELECT    branchid
                                                  FROM      branch
                                                  WHERE     selfiniyear = 0 )
                             )
                        )
		
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM bakdly
            WHERE   NOT EXISTS ( SELECT vchcode
                                 FROM   dlyndx
                                 WHERE  bakdly.vchcode = dlyndx.vchcode )
            IF @@Error <> 0 
                GOTO error1	
            DELETE  FROM dbo.BakDlyDetaiL
            WHERE   dlyorder NOT IN ( SELECT    dlyorder
                                      FROM      bakdly )
            IF @@Error <> 0 
                GOTO error1	
	-- 删除已执行完的订单  
            DELETE  bakdlyorderdetail
            FROM    bakdlyorderdetail d,
                    BakDlyOrder b,
                    DlyNdxOrder o
            WHERE   d.dlyorder = b.dlyorder
                    AND b.vchcode = o.vchcode
                    AND o.ifcheck = '2'
			--AND (o.vchtype in (7,8,211,214) OR (o.vchtype =221))
            IF @@error <> 0 
                GOTO error1
            DELETE  BakDlyOrder
            FROM    BakDlyOrder b,
                    DlyNdxOrder o
            WHERE   b.vchcode = o.vchcode
                    AND o.ifcheck = '2'
            IF @@error <> 0 
                GOTO error1
            DELETE  FROM DlyNdxOrder
            WHERE   ifcheck = '2'
            IF @@error <> 0 
                GOTO error1
	                     --Add end         
            DELETE  FROM inigoodsstocks
            WHERE   ktypeid IN (
                    SELECT  typeid
                    FROM    stock
                    WHERE   branchid IN ( SELECT    branchid
                                          FROM      branch
                                          WHERE     selfiniyear = 0 ) )
            IF @@Error <> 0 
                GOTO error1

            DELETE  FROM inigoodsdetail
            WHERE   orderid NOT IN ( SELECT orderid
                                     FROM   inigoodsstocks )
            IF @@Error <> 0 
                GOTO error1
            
            --清除零售计划设置相关  （最后确认不删除了 2012-8-22）      
			--delete  from SalePlanBillDetail where   branchid IN ( SELECT    branchid FROM      branch WHERE     selfiniyear = 0 ) 
			--delete  from SalePlanBill  where VchCode not in (select VchCode from SalePlanBillDetail)
			--delete  from SalePlanConfig  where SalePlanID not in (select SalePlanID FROM SalePlanBill)
        END
    ELSE  --加盟年结
        BEGIN
        --清除零售计划设置相关 （最后确认不删除了 2012-8-22）   
		--delete  from SalePlanBillDetail  where Branchid =@branchid
        --delete  from SalePlanBill  where VchCode not in (select VchCode from SalePlanBillDetail)
		--delete  from SalePlanConfig  where SalePlanID not in (select SalePlanID FROM SalePlanBill)

		----清除智能配货相关
		delete from AutoPhTitleData where MainBranchid =@branchid
		delete from AutoPhOrderTitleData  where MainBranchid=@branchid
		delete from AutoPhGrdData where etypeid not in (select etypeid from AutoPhTitleData)
		delete from AutoPhOrderGrdData  where etypeid not in (select etypeid from AutoPhOrderTitleData)

		--清除退货调整单(过期的）
		delete from ChangeBillNdx  where btypeid in ( select btypeid from btype where branchid=@branchid) AND
		dateadd(d,effectiveDays,billdate)<Convert(datetime,convert(varchar(10),year(getdate()))+'-'+right('0'+convert(varchar(10),month(getdate())),2)+'-'+right('0'+convert(varchar(10),day(getdate())),2))
		delete from ChangeBillData where billcode not in (select billcode from ChangeBillNdx)

		delete from  btyperetqty where outdate<getdate() and btypeid in ( select btypeid from btype where branchid =@branchid)
		AND (Vchtype<>0 OR (Vchtype =0 AND VchCode NOT IN (select VchCode from ChangeBillNdx)))
		delete from  btyperettotal where outdate<getdate()  and btypeid in ( select btypeid from btype where branchid =@branchid)
		AND (Vchtype<>0 OR (Vchtype =0 AND VchCode NOT IN (select VchCode from ChangeBillNdx)))
	
		--------清除POS小票及促销--------(POS小票要已经结存的才删除）
		--  清除新POS4.1相关
            DELETE  dbo.tpx_SaleIndex
            WHERE   JTypeId = @branchid
                    AND draftVchcode <> 0
            DELETE  dbo.tpx_SaleList
            WHERE   ZBKeyId NOT IN ( SELECT  keyId
                                        FROM    dbo.tpx_SaleIndex )
            DELETE  dbo.tpx_SaleVipList
            WHERE   ZBKeyId NOT IN ( SELECT  keyId
                                        FROM    dbo.tpx_SaleIndex )
	    
		    DELETE dbo.tpx_SalePayList WHERE ZBKeyId NOT IN(SELECT keyId FROM dbo.tpx_SaleIndex)
		    DELETE dbo.tpx_SaleManList WHERE cbKeyId NOT IN(SELECT keyId FROM dbo.tpx_SaleList)	
		    

		--删除POS结存(PDVchCode<>0表明已生成后台盘点单）
            DELETE  FROM dbo.tpx_CheckNdx
            WHERE   ktypeid IN ( SELECT typeid
                                 FROM   stock
                                 WHERE  branchid = @branchid )
                    AND PDVchCode <> 0
            DELETE  FROM dbo.tpx_CheckList
            WHERE   ZBkeyid NOT IN ( SELECT   keyid
                                       FROM     dbo.tpx_CheckNdx )

			DELETE dbo.tpx_CheckPointNdx WHERE Audit=1
			
		-- 先删除适用范围 -- 机构(非单独年结的机构)，再把无适用范围的其它相关表删除
            DELETE  dbo.tpx_CXBillBound
            WHERE   ktypeid = @branchid
                    AND EXISTS ( SELECT 1
                                 FROM   dbo.tpx_CXBillIndex
                                 WHERE  tpx_CXBillIndex.BILLNUMBERID = tpx_CXBillBound.BILLNUMBERID
                                        AND @Today > ENDDATE )
            DELETE  dbo.tpx_CXBillIndex
            WHERE   @Today > ENDDATE
                    AND billnumberid NOT IN ( SELECT    billnumberid
                                              FROM      tpx_CXBillBound ) 		
            DELETE  dbo.tpx_CXBillComD
            WHERE   billnumberid NOT IN ( SELECT    billnumberid
                                          FROM      dbo.tpx_CXBillIndex )
            DELETE  dbo.tpx_CXBillCom
            WHERE   billnumberid NOT IN ( SELECT    billnumberid
                                          FROM      dbo.tpx_CXBillIndex )
            DELETE  dbo.tpx_CXBillLarg
            WHERE   billnumberid NOT IN ( SELECT    billnumberid
                                          FROM      dbo.tpx_CXBillIndex )
            DELETE  dbo.tpx_CXBillHand
            WHERE   billnumberid NOT IN ( SELECT    billnumberid
                                          FROM      dbo.tpx_CXBillIndex )
            DELETE  dbo.tpx_CXBillSpec
            WHERE   billnumberid NOT IN ( SELECT    billnumberid
                                          FROM      dbo.tpx_CXBillIndex )


            DELETE  FROM DlyData
            WHERE   branchid = @branchid
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM Dlya
            WHERE   branchid = @branchid
            IF @@Error <> 0 
                GOTO error1
	
            DELETE  FROM DlyDataDetail
            WHERE   dlyorder NOT IN ( SELECT    dlyorder
                                      FROM      DlyData )
            IF @@Error <> 0 
                GOTO error1
	
		
            DELETE  FROM bakdly
            WHERE   EXISTS ( SELECT vchcode
                             FROM   dlyndx
                             WHERE  draft NOT IN ( 1, 9 )
                                    AND bakdly.vchcode = dlyndx.vchcode
                                    AND ( ( vchtype NOT IN ( 222, 224, 232,
                                                             234 )
                                            AND ( branchid = @branchid
                                                  OR branchid2 = @branchid
                                                )
                                          )
                                          OR ( vchtype IN ( 232 )
                                               AND branchid = @branchid
                                             )
                                          OR ( vchtype IN ( 234 )
                                               AND branchid2 = @branchid
                                             )
                                        ) )


            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM DlyNdx
            WHERE   draft NOT IN ( 1, 9 )
                    AND ( ( vchtype NOT IN ( 222, 224, 232, 234 )
                            AND ( branchid = @branchid
                                  OR branchid2 = @branchid
                                )
                          )
                          OR ( vchtype IN ( 232 )
                               AND branchid = @branchid
                             )
                          OR ( vchtype IN ( 234 )
                               AND branchid2 = @branchid
                             )
                        )

		
            IF @@Error <> 0 
                GOTO error1

            DELETE  FROM bakdly
            WHERE   NOT EXISTS ( SELECT vchcode
                                 FROM   dlyndx
                                 WHERE  bakdly.vchcode = dlyndx.vchcode )
            IF @@Error <> 0 
                GOTO error1	
            DELETE  FROM dbo.BakDlyDetaiL
            WHERE   dlyorder NOT IN ( SELECT    dlyorder
                                      FROM      bakdly )
            IF @@Error <> 0 
                GOTO error1	
	-- 删除已执行完的订单  
            DELETE  bakdlyorderdetail
            FROM    bakdlyorderdetail d,
                    BakDlyOrder b,
                    DlyNdxOrder o
            WHERE   d.dlyorder = b.dlyorder
                    AND b.vchcode = o.vchcode
                    AND o.ifcheck = '2'
			--AND (o.vchtype in (7,8,211,214) OR (o.vchtype =221))
            IF @@error <> 0 
                GOTO error1
            DELETE  BakDlyOrder
            FROM    BakDlyOrder b,
                    DlyNdxOrder o
            WHERE   b.vchcode = o.vchcode
                    AND o.ifcheck = '2'
            IF @@error <> 0 
                GOTO error1
            DELETE  FROM DlyNdxOrder
            WHERE   ifcheck = '2'
            IF @@error <> 0 
                GOTO error1
	                     --Add end         
	  
	           
            DELETE  FROM inigoodsstocks
            WHERE   ktypeid IN ( SELECT typeid
                                 FROM   stock
                                 WHERE  branchid = @branchid )
            IF @@Error <> 0 
                GOTO error1

            DELETE  FROM inigoodsdetail
            WHERE   orderid NOT IN ( SELECT orderid
                                     FROM   inigoodsstocks )
            IF @@Error <> 0 
                GOTO error1
        END
	-- 将库存转到期初

    DECLARE @cOrderid INT,
        @cPTYPEID VARCHAR(50),
        @cKTYPEID VARCHAR(50),
        @cQty NUMERIC(24, 10),
        @cPRICE NUMERIC(24, 10),
        @cTotal NUMERIC(24, 10),
        @cGoodsOrder INT,
        @nOrderid INT
    IF @branchid = '' 
        DECLARE ini_cursor CURSOR
            FOR SELECT  orderid,
                        PtypeId,
                        KtypeId,
                        Qty,
                        Price,
                        Total,
                        GoodsOrder
                FROM    goodsstocks
                WHERE   ktypeid IN (
                        SELECT  typeid
                        FROM    stock
                        WHERE   branchid IN ( SELECT    branchid
                                              FROM      branch
                                              WHERE     selfiniyear = 0 ) )
    ELSE 
        DECLARE ini_cursor CURSOR
            FOR SELECT  orderid,
                        PtypeId,
                        KtypeId,
                        Qty,
                        Price,
                        Total,
                        GoodsOrder
                FROM    goodsstocks
                WHERE   ktypeid IN ( SELECT typeid
                                     FROM   stock
                                     WHERE  branchid = @branchid )
    OPEN ini_cursor 
    FETCH NEXT FROM ini_cursor INTO @cOrderid, @cPTYPEID, @cKTYPEID, @cQty,
        @cPRICE, @cTotal, @cGoodsOrder
    WHILE @@fetch_status = 0
        BEGIN
		
            INSERT  INTO inigoodsstocks
                    (
                      PTYPEID,
                      KTYPEID,
                      Qty,
                      PRICE,
                      Total,
                      GoodsOrder
                    )
            VALUES  (
                      @cPTYPEID,
                      @cKTYPEID,
                      @cQty,
                      @cPRICE,
                      @cTotal,
                      @cGoodsOrder
                    )
            IF @@Error <> 0 
                GOTO error10

            SELECT  @nORDERID = @@identity
            INSERT  INTO inigoodsdetail
                    (
                      ORDERID,
                      SIZEID,
                      COLORID,
                      QTY,
                      total
                    )
                    SELECT  @nORDERID,
                            SIZEID,
                            COLORID,
                            QTY,
                            total
                    FROM    goodsStockDetail
                    WHERE   orderid = @corderid
            IF @@Error <> 0 
                GOTO error10		
            FETCH NEXT FROM ini_cursor INTO @cOrderid, @cPTYPEID, @cKTYPEID,
                @cQty, @cPRICE, @cTotal, @cGoodsOrder
		
        END
	
    CLOSE ini_cursor
    DEALLOCATE ini_cursor
	
	/*
	set identity_insert iniCommission on
	truncate table   iniCommission
	insert into iniCommission (PTYPEID,BTYPEID,TYPE,QTY,TOTAL,PRODATE,COSTTOTAL,tax,taxtotal,dlyorder) 
	                        select  PTYPEID,BTYPEID,TYPE,QTY,0,PRODATE,COSTTOTAL,tax,taxtotal,dlyorder  from Commission
	if @@Error<>0 goto error1
	set identity_insert iniCommission off
	
	truncate table   iniCommissiondetail		
	
	insert into iniCommissiondetail select  *  from Commissiondetail
	if @@Error<>0 goto error1
	*/

    IF @branchid = '' --总部年结，同时也要年结非独立年结的加盟商
        BEGIN
            DELETE  FROM GoodsStocks
            WHERE   ktypeid IN (
                    SELECT  typeid
                    FROM    stock
                    WHERE   branchid IN ( SELECT    branchid
                                          FROM      branch
                                          WHERE     selfiniyear = 0 ) )
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM GoodsStockdetail
            WHERE   orderid NOT IN ( SELECT orderid
                                     FROM   GoodsStocks )
            DELETE  FROM Gatheringdly
            WHERE    (Vchcode<>-1 AND vchcode NOT IN ( SELECT vchcode  FROM   dlyndx ))
                     OR gatheringvchcode NOT IN ( SELECT vchcode      FROM   dlyndx )
            
            DELETE  FROM Gatheringdly WHERE Vchcode=-1 AND BTypeID in (select BTypeID from Branch where selfiniyear = 0)
            
	--	清除过帐标志
            UPDATE  sysdata
            SET     subvalue = 0
            WHERE   subname = 'iniover'
            IF @@Error <> 0 
                GOTO error1
            UPDATE  sysdata
            SET     subvalue = 1
            WHERE   subname = 'period'
            IF @@Error <> 0 
                GOTO error1
	--	清除盘点标志
            UPDATE  sysdata
            SET     [subvalue] = ''
            WHERE   [subname] = 'PdReady'
            IF @@error <> 0 
                GOTO error1 
	
            UPDATE  sysdata
            SET     [subvalue] = ''
            WHERE   [subname] = 'JMDPdReady'
            IF @@error <> 0 
                GOTO error1 
	--	清除科目
            UPDATE  atype
            SET     ttl00 = ttl00 + total
            WHERE   branchid IN ( SELECT    branchid
                                  FROM      branch
                                  WHERE     selfiniyear = 0 )
            IF @@Error <> 0 
                GOTO error1
            UPDATE  atype
            SET     TTL01 = 0,
                    TTL02 = 0,
                    TTL03 = 0,
                    TTL04 = 0,
                    TTL05 = 0,
                    TTL06 = 0,
                    TTL07 = 0,
                    TTL08 = 0,
                    TTL09 = 0,
                    TTL10 = 0,
                    TTL11 = 0,
                    TTL12 = 0,
                    Total = 0
            WHERE   branchid IN ( SELECT    branchid
                                  FROM      branch
                                  WHERE     selfiniyear = 0 )
            IF @@Error <> 0 
                GOTO error1
            UPDATE  atype
            SET     ttl00 = 0
            WHERE   LEFT(typeid, 5) = '00003'
                    OR LEFT(typeid, 5) = '00004'
                    OR LEFT(typeid, 5) = '00005'
                    AND branchid IN ( SELECT    branchid
                                      FROM      branch
                                      WHERE     selfiniyear = 0 )
            IF @@Error <> 0 
                GOTO error1
	--修改应收应付
            UPDATE  Branchbtype
            SET     ArTotal00 = 0,
                    Aptotal00 = 0
            WHERE   ( LEFT(btypeid, 5) = '00001'
                      OR LEFT(btypeid, 5) = '00007'
                    )
                    AND ApTotal = 0
                    AND ArTotal = 0
                    AND branchid IN ( SELECT    branchid
                                      FROM      branch
                                      WHERE     selfiniyear = 0 )
	
            UPDATE  Branchbtype
            SET     ArTotal00 = 0,
                    Aptotal00 = 0
            WHERE   LEFT(btypeid, 5) IN ( '00002', '00005', '00004', '00003',
                                          '00006' )
                    AND ApTotal = 0
                    AND ArTotal = 0
                    AND branchid IN ( SELECT    branchid
                                      FROM      branch
                                      WHERE     selfiniyear = 0 )
	
            UPDATE  Branchbtype
            SET     ArTotal00 = CASE WHEN ApTotal - ArTotal < 0
                                     THEN -( ApTotal - ArTotal )
                                     ELSE 0
                                END,
                    Aptotal00 = CASE WHEN ApTotal - ArTotal > 0
                                     THEN ( ApTotal - ArTotal )
                                     ELSE 0
                                END,
					prepayment00=prepayment,
					deposit00=deposit
            WHERE   branchid IN ( SELECT    branchid
                                  FROM      branch
                                  WHERE     selfiniyear = 0 )
	
            IF @@Error <> 0 
                GOTO error1
            UPDATE  Branchbtype
            SET     artotal00 = artotal00 - aptotal00
            WHERE   LEFT(btypeid, 5) NOT IN ( '00001', '00007' )
                    AND branchid IN ( SELECT    branchid
                                      FROM      branch
                                      WHERE     selfiniyear = 0 )
            IF @@Error <> 0 
                GOTO error1
            UPDATE  Branchbtype
            SET     aptotal00 = 0
            WHERE   LEFT(btypeid, 5) NOT IN ( '00001', '00007' )
                    AND branchid IN ( SELECT    branchid
                                      FROM      branch
                                      WHERE     selfiniyear = 0 )
            IF @@Error <> 0 
                GOTO error1
            UPDATE  Branchbtype
            SET     aptotal00 = aptotal00 - artotal00
            WHERE   LEFT(btypeid, 5) = '00001'
                    OR LEFT(btypeid, 5) = '00007'
                    AND branchid IN ( SELECT    branchid
                                      FROM      branch
                                      WHERE     selfiniyear = 0 )
            IF @@Error <> 0 
                GOTO error1
            UPDATE  Branchbtype
            SET     artotal00 = 0
            WHERE   LEFT(btypeid, 5) = '00001'
                    OR LEFT(btypeid, 5) = '00007'
                    AND branchid IN ( SELECT    branchid
                                      FROM      branch
                                      WHERE     selfiniyear = 0 )
            IF @@Error <> 0 
                GOTO error1
            UPDATE  Branchbtype
            SET     Artotal = 0, Aptotal = 0,prepayment=0,
					deposit=0
            WHERE   branchid IN ( SELECT    branchid
                                  FROM      branch
                                  WHERE     selfiniyear = 0 )
            IF @@Error <> 0 
                GOTO error1
        END
    ELSE --加盟年结
        BEGIN
            DELETE  FROM GoodsStocks
            WHERE   ktypeid IN ( SELECT typeid
                                 FROM   stock
                                 WHERE  branchid = @branchid )
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM GoodsStockdetail
            WHERE   orderid NOT IN ( SELECT orderid
                                     FROM   GoodsStocks )
            DELETE  FROM Gatheringdly
            WHERE    (Vchcode<>-1 AND vchcode NOT IN ( SELECT vchcode  FROM   dlyndx ))
                     OR gatheringvchcode NOT IN ( SELECT vchcode      FROM   dlyndx )
                     
            DELETE  FROM Gatheringdly WHERE Vchcode=-1 AND BTypeID in (select BTypeID from Branch where BranchID =@branchid)
		/*
	--	清除过帐标志
		Update sysdata	Set subvalue=0	Where subname='iniover'
		if @@Error<>0 goto error1
		update sysdata set subvalue=1 where subname='period'
		if @@Error<>0 goto error1
	--	清除盘点标志
		Update sysdata set [subvalue]='' Where [subname]= 'PdReady'
		if @@error<>0 goto error1 
	
		Update sysdata set [subvalue]='' Where [subname]= 'JMDPdReady'
		if @@error<>0 goto error1 
		*/
	--	清除科目
            UPDATE  atype
            SET     ttl00 = ttl00 + total
            WHERE   branchid = @branchid
            IF @@Error <> 0 
                GOTO error1
            UPDATE  atype
            SET     TTL01 = 0,
                    TTL02 = 0,
                    TTL03 = 0,
                    TTL04 = 0,
                    TTL05 = 0,
                    TTL06 = 0,
                    TTL07 = 0,
                    TTL08 = 0,
                    TTL09 = 0,
                    TTL10 = 0,
                    TTL11 = 0,
                    TTL12 = 0,
                    Total = 0
            WHERE   branchid = @branchid
            IF @@Error <> 0 
                GOTO error1
            UPDATE  atype
            SET     ttl00 = 0
            WHERE   LEFT(typeid, 5) = '00003'
                    OR LEFT(typeid, 5) = '00004'
                    OR LEFT(typeid, 5) = '00005'
                    AND branchid = @branchid
            IF @@Error <> 0 
                GOTO error1
	--修改应收应付
            UPDATE  Branchbtype
            SET     ArTotal00 = 0,
                    Aptotal00 = 0
            WHERE   LEFT(btypeid, 5) = '00001'
                    AND ApTotal = 0
                    AND ArTotal = 0
                    AND branchid = @branchid
	
            UPDATE  Branchbtype
            SET     ArTotal00 = 0,
                    Aptotal00 = 0
            WHERE   LEFT(btypeid, 5) IN ( '00002', '00005', '00004', '00003',
                                          '00006' )
                    AND ApTotal = 0
                    AND ArTotal = 0
                    AND branchid = @branchid
	
            UPDATE  Branchbtype
            SET     ArTotal00 = CASE WHEN ApTotal - ArTotal < 0
                                     THEN -( ApTotal - ArTotal )
                                     ELSE 0
                                END,
                    Aptotal00 = CASE WHEN ApTotal - ArTotal > 0
                                     THEN ( ApTotal - ArTotal )
                                     ELSE 0
                                END,
					prepayment00=prepayment,
					deposit00=deposit
            WHERE   branchid = @branchid
	
            IF @@Error <> 0 
                GOTO error1
            UPDATE  Branchbtype
            SET     artotal00 = artotal00 - aptotal00
            WHERE   LEFT(btypeid, 5) NOT IN ( '00001', '00007' )
                    AND branchid = @branchid
            IF @@Error <> 0 
                GOTO error1
            UPDATE  Branchbtype
            SET     aptotal00 = 0
            WHERE   LEFT(btypeid, 5) NOT IN ( '00001', '00007' )
                    AND branchid = @branchid
            IF @@Error <> 0 
                GOTO error1
            UPDATE  Branchbtype
            SET     aptotal00 = aptotal00 - artotal00
            WHERE   LEFT(btypeid, 5) = '00001'
                    OR LEFT(btypeid, 5) = '00007'
                    AND branchid = @branchid
            IF @@Error <> 0 
                GOTO error1
            UPDATE  Branchbtype
            SET     artotal00 = 0
            WHERE   LEFT(btypeid, 5) = '00001'
                    OR LEFT(btypeid, 5) = '00007'
                    AND branchid = @branchid
            IF @@Error <> 0 
                GOTO error1
            UPDATE  Branchbtype
            SET     Artotal = 0, Aptotal = 0,prepayment=0,
					deposit=0
            WHERE   branchid = @branchid
            IF @@Error <> 0 
                GOTO error1
        END
	
	
--清除月结存信息表
    IF @branchid = '' 
        BEGIN
            DELETE  FROM monthproc
            WHERE   period <> 13
            UPDATE  monthproc
            SET     startdate = CONVERT(VARCHAR(4), YEAR(GETDATE())) + '-'
                    + RIGHT('0' + LTRIM(CONVERT(VARCHAR(2), MONTH(GETDATE()))),
                            2) + '-' + RIGHT('0'
                                             + LTRIM(CONVERT(VARCHAR(2), DAY(GETDATE()))),
                                             2)
            WHERE   period = 13
            IF @@Error <> 0 
                GOTO error1
        END
 	/*
      if @@Error<>0 goto error1
      truncate table posretailbill
      if @@Error<>0 goto error1
      truncate table PosRetailBillDetail
      if @@Error<>0 goto error1
      truncate table POSRetailBillFreeze
      if @@Error<>0 goto error1
      truncate table PosRetailBillDetailFreeze
      if @@Error<>0 goto error1
      truncate table shift  --好像是上下传的东东
      if @@Error<>0 goto error1
	*/
--清除盘点状态(清除盘点生成的草稿）


    IF @branchid = '' 
        BEGIN	
            DELETE  bakdlydetail
            WHERE   dlyorder IN (
                    SELECT  dlyorder
                    FROM    bakdly
                    WHERE   vchcode IN (
                            SELECT  vchcode
                            FROM    dlyndx
                            WHERE   vchtype IN ( 9, 14, 140, 141 )
                                    AND ISNULL(expandid, '') <> ''
                                    AND branchid IN (
                                    SELECT  branchid
                                    FROM    branch
                                    WHERE   selfiniyear = 0 ) ) )
            IF @@Error <> 0 
                GOTO error1
            DELETE  bakdly
            WHERE   vchcode IN (
                    SELECT  vchcode
                    FROM    dlyndx
                    WHERE   vchtype IN ( 9, 14, 140, 141 )
                            AND ISNULL(expandid, '') <> ''
                            AND branchid IN ( SELECT    branchid
                                              FROM      branch
                                              WHERE     selfiniyear = 0 ) )
            IF @@Error <> 0 
                GOTO error1
            DELETE  dlyndx
            WHERE   vchtype IN ( 9, 14, 140, 141 )
                    AND ISNULL(expandid, '') <> ''
                    AND branchid IN ( SELECT    branchid
                                      FROM      branch
                                      WHERE     selfiniyear = 0 )
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM stockpdstate
            WHERE   ktypeid IN (
                    SELECT  typeid
                    FROM    stock
                    WHERE   branchid IN ( SELECT    branchid
                                          FROM      branch
                                          WHERE     selfiniyear = 0 ) )
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM goodsstockbackup
            WHERE   ktypeid IN (
                    SELECT  typeid
                    FROM    stock
                    WHERE   branchid IN ( SELECT    branchid
                                          FROM      branch
                                          WHERE     selfiniyear = 0 ) )
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM dlyndxchecked
            WHERE   branchid IN ( SELECT    branchid
                                  FROM      branch
                                  WHERE     selfiniyear = 0 )
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM dlychecked
            WHERE   ktypeid IN (
                    SELECT  typeid
                    FROM    stock
                    WHERE   branchid IN ( SELECT    branchid
                                          FROM      branch
                                          WHERE     selfiniyear = 0 ) )
            IF @@Error <> 0 
                GOTO error1
        END
    ELSE 
        BEGIN
            DELETE  bakdlydetail
            WHERE   dlyorder IN (
                    SELECT  dlyorder
                    FROM    bakdly
                    WHERE   vchcode IN ( SELECT vchcode
                                         FROM   dlyndx
                                         WHERE  vchtype IN ( 9, 14, 140, 141 )
                                                AND ISNULL(expandid, '') <> ''
                                                AND branchid = @branchid ) )
            IF @@Error <> 0 
                GOTO error1
            DELETE  bakdly
            WHERE   vchcode IN ( SELECT vchcode
                                 FROM   dlyndx
                                 WHERE  vchtype IN ( 9, 14, 140, 141 )
                                        AND ISNULL(expandid, '') <> ''
                                        AND branchid = @branchid )
            IF @@Error <> 0 
                GOTO error1
            DELETE  dlyndx
            WHERE   vchtype IN ( 9, 14, 140, 141 )
                    AND ISNULL(expandid, '') <> ''
                    AND branchid = @branchid
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM stockpdstate
            WHERE   ktypeid IN ( SELECT typeid
                                 FROM   stock
                                 WHERE  branchid = @branchid )
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM goodsstockbackup
            WHERE   ktypeid IN ( SELECT typeid
                                 FROM   stock
                                 WHERE  branchid = @branchid )
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM dlyndxchecked
            WHERE   branchid = @branchid
            IF @@Error <> 0 
                GOTO error1
            DELETE  FROM dlychecked
            WHERE   ktypeid IN ( SELECT typeid
                                 FROM   stock
                                 WHERE  branchid = @branchid )
            IF @@Error <> 0 
                GOTO error1
        END



-----将VIP积分放到期初去

--新规则： 
--1、总部年结
--a、（非独立年结加盟机构+内部机构）建的卡类型相关VIP信息作清除
--b、独立加盟机构，卡类型为总部的相关VIP清除
--2、加盟年结,清除卡类型为该加盟机构的相关VIP
-- vipcards.handoutdept表示发卡操作员的属加盟机构，为空表明内部 handoutdept=''肯定表明是内部机构所发卡类型
    IF @Branchid = '' --总部年结时，才处理VIP相关(有改变规则）
        BEGIN
            DELETE  vipcards
            WHERE   deleted = 1
                    AND ( handoutdept = ''
                          OR cardtypeid IN (
                          SELECT    orderid
                          FROM      vipcardtypes
                          WHERE     LEFT(branchid, 5) = '00001'
                                    OR branchid IN ( SELECT branchid
                                                     FROM   branch
                                                     WHERE  selfiniyear = 0 ) )
                        )
            IF @@Error <> 0 
                GOTO error1
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM VIpCardIntegralTransact
            WHERE   cardid IN (
                    SELECT  cardid
                    FROM    vipcards
                    WHERE   ( handoutdept = ''
                              OR cardtypeid IN (
                              SELECT    orderid
                              FROM      vipcardtypes
                              WHERE     LEFT(branchid, 5) = '00001'
                                        OR branchid IN (
                                        SELECT  branchid
                                        FROM    branch
                                        WHERE   selfiniyear = 0 ) )
                            ) )
            IF @@error <> 0 
                GOTO error1	
	-- 	Truncate table	VIPCardSaveMoney
	-- 	if @@error<>0 goto error1	
            DELETE  FROM VIPCardIntegralSend
            WHERE   cardid IN (
                    SELECT  cardid
                    FROM    vipcards
                    WHERE   ( handoutdept = ''
                              OR cardtypeid IN (
                              SELECT    orderid
                              FROM      vipcardtypes
                              WHERE     LEFT(branchid, 5) = '00001'
                                        OR branchid IN (
                                        SELECT  branchid
                                        FROM    branch
                                        WHERE   selfiniyear = 0 ) )
                            ) )
            IF @@error <> 0 
                GOTO error1	
	--清除积分历史
            DELETE  FROM vipintegraldetail
            WHERE   cardid IN (
                    SELECT  cardid
                    FROM    vipcards
                    WHERE   ( handoutdept = ''
                              OR cardtypeid IN (
                              SELECT    orderid
                              FROM      vipcardtypes
                              WHERE     LEFT(branchid, 5) = '00001'
                                        OR branchid IN (
                                        SELECT  branchid
                                        FROM    branch
                                        WHERE   selfiniyear = 0 ) )
                            ) )
            IF @@error <> 0 
                GOTO error1	
	-----将VIP储值卡使用清单删除
            DELETE  FROM cardFillList
            WHERE   cardid IN (
                    SELECT  cardid
                    FROM    vipcards
                    WHERE   ( handoutdept = ''
                              OR cardtypeid IN (
                              SELECT    orderid
                              FROM      vipcardtypes
                              WHERE     LEFT(branchid, 5) = '00001'
                                        OR branchid IN (
                                        SELECT  branchid
                                        FROM    branch
                                        WHERE   selfiniyear = 0 ) )
                            ) )
            IF @@error <> 0 
                GOTO error1
	-----将VIP储值门店锁定取消
            UPDATE  VipCards
            SET     iftransfered = 0
            IF @@error <> 0 
                GOTO error1
	----重新插入期初
            INSERT  INTO VIPIntegralDetail
                    (
                      ktypeid,
                      BatchNo,
                      ConsumeAdd,
                      IntegralAdd,
                      AddFlag,
                      CardID,
                      date,
                      vchcode,
                      ConsumeTotal,
                      IntegralConsume,
                      Integral,
                      IntegralTotal
                    )
                    SELECT  '00001',
                            -1,
                            ISNULL(b.allconsume, 0),
                            ISNULL(b.integral2, 0),
                            ISNULL(b.ExpandNo, 0),
                            a.cardid,
                            CONVERT(VARCHAR(10), GETDATE(), 120),
                            0,
                            a.allconsume,
                            a.ljxfjfje,
                            a.allintegral,
                            a.allintegral
                    FROM    vipcards a
                            LEFT JOIN vipcardexpand b ON a.cardtypeid = b.cardid
                    WHERE   ( a.handoutdept = ''
                              OR a.cardtypeid IN (
                              SELECT    orderid
                              FROM      vipcardtypes
                              WHERE     LEFT(branchid, 5) = '00001'
                                        OR branchid IN (
                                        SELECT  branchid
                                        FROM    branch
                                        WHERE   selfiniyear = 0 ) )
                            )
            IF @@error <> 0 
                GOTO error1	
-----
        END
    ELSE --加盟年结
        BEGIN
            DELETE  vipcards
            WHERE   deleted = 1
                    AND cardtypeid IN ( SELECT  orderid
                                        FROM    vipcardtypes
                                        WHERE   branchid = @branchid )
            IF @@Error <> 0 
                GOTO error1
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM VIpCardIntegralTransact
            WHERE   cardid IN (
                    SELECT  cardid
                    FROM    vipcards
                    WHERE   cardtypeid IN ( SELECT  orderid
                                            FROM    vipcardtypes
                                            WHERE   branchid = @branchid ) )
            IF @@error <> 0 
                GOTO error1	
	-- 	Truncate table	VIPCardSaveMoney
	-- 	if @@error<>0 goto error1	
            DELETE  FROM VIPCardIntegralSend
            WHERE   cardid IN (
                    SELECT  cardid
                    FROM    vipcards
                    WHERE   cardtypeid IN ( SELECT  orderid
                                            FROM    vipcardtypes
                                            WHERE   branchid = @branchid ) )
            IF @@error <> 0 
                GOTO error1	
	--清除积分历史
            DELETE  FROM vipintegraldetail
            WHERE   cardid IN (
                    SELECT  cardid
                    FROM    vipcards
                    WHERE   cardtypeid IN ( SELECT  orderid
                                            FROM    vipcardtypes
                                            WHERE   branchid = @branchid ) )
            IF @@error <> 0 
                GOTO error1	
	-----将VIP储值卡使用清单删除
            DELETE  FROM cardFillList
            WHERE   cardid IN (
                    SELECT  cardid
                    FROM    vipcards
                    WHERE   cardtypeid IN ( SELECT  orderid
                                            FROM    vipcardtypes
                                            WHERE   branchid = @branchid ) )
            IF @@error <> 0 
                GOTO error1
	-----将VIP储值门店锁定取消
            UPDATE  VipCards
            SET     iftransfered = 0
            IF @@error <> 0 
                GOTO error1
	----重新插入期初
            INSERT  INTO VIPIntegralDetail
                    (
                      ktypeid,
                      BatchNo,
                      ConsumeAdd,
                      IntegralAdd,
                      AddFlag,
                      CardID,
                      date,
                      vchcode,
                      ConsumeTotal,
                      IntegralConsume,
                      Integral,
                      IntegralTotal
                    )
                    SELECT  '00001',
                            -1,
                            ISNULL(b.allconsume, 0),
                            ISNULL(b.integral2, 0),
                            ISNULL(b.ExpandNo, 0),
                            a.cardid,
                            CONVERT(VARCHAR(10), GETDATE(), 120),
                            0,
                            a.allconsume,
                            a.ljxfjfje,
                            a.allintegral,
                            a.allintegral
                    FROM    vipcards a
                            LEFT JOIN vipcardexpand b ON a.cardtypeid = b.cardid
                    WHERE   a.cardtypeid IN ( SELECT    orderid
                                              FROM      vipcardtypes
                                              WHERE     branchid = @branchid )
            IF @@error <> 0 
                GOTO error1	
        END

--总部年结时，且所有加盟商都是非单独年结时才处理单据编号
    IF @Branchid = ''
        AND NOT EXISTS ( SELECT TOP 1
                                1
                         FROM   branch
                         WHERE  selfiniyear = 1 ) 
        BEGIN
  -------------------- 清除单据最大编号
            TRUNCATE TABLE Billdaynumber
            IF @@error <> 0 
                GOTO error1
            TRUNCATE TABLE Billmonthnumber
            IF @@error <> 0 
                GOTO error1

            UPDATE  vchtype
            SET     SNMAX = 0
            FROM    vchtype 
            IF @@error <> 0 
                GOTO error1
   
            UPDATE  sysdata
            SET     SubValue = 0
            WHERE   subname = 'SNMax'
            IF @@error <> 0 
                GOTO error1
        END   
--总部年结时，且所有加盟商都是非单独年结时才处理单据编号
   --清除上下传表
    TRUNCATE TABLE transbill
    IF @@error <> 0 
        GOTO error1
    TRUNCATE TABLE transbilldetail
    IF @@error <> 0 
        GOTO error1
   
   
   -- 判断是否删除停用商品
   --默认删除,总部年结，且所有加盟商都是非单独年结时，才删除商品
    SET @ifdelptype = 1
    IF @ifdelptype = 1
        AND @branchid = ''
        AND NOT EXISTS ( SELECT TOP 1
                                1
                         FROM   branch
                         WHERE  selfiniyear = 1 ) 
        BEGIN
            DELETE  FROM ptype
            WHERE   Stop = 1
                    AND typeid NOT IN (
                    SELECT  p.typeid
                    FROM    ptype p,
                            ( SELECT    ptypeid
                              FROM      IniGoodsStocks
                              UNION ALL
                              SELECT    ptypeid
                              FROM      dbo.IniCommission
                              UNION ALL
                              SELECT    ptypeid
                              FROM      bakdly
                            ) i
                    WHERE   LEFT(i.ptypeid, LEN(p.typeid)) = p.typeid )


            IF @@error <> 0 
                GOTO error1	 
            DELETE  FROM ptypebar
            WHERE   ptypeid NOT IN ( SELECT typeid
                                     FROM   ptype )
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM MultiBarList
            WHERE   ptypeid NOT IN ( SELECT typeid
                                     FROM   ptype )
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM ptypeprice
            WHERE   ptypeid NOT IN ( SELECT typeid
                                     FROM   Ptype )
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM dbo.BtypeSupply
            WHERE   ptypeid NOT IN ( SELECT typeid
                                     FROM   ptype )
            IF @@error <> 0 
                GOTO error1	
            UPDATE  ptype
            SET     SonNum = ISNULL(( SELECT    COUNT(Typeid)
                                      FROM      ptype
                                      WHERE     a.typeid = Parid
                                                AND deleted = 0
                                    ), 0)
            FROM    ptype a
            IF @@error <> 0 
                GOTO error1	
            UPDATE  ptype
            SET     SonCount = ISNULL(( SELECT  CAST(MAX(RIGHT(typeid, 5)) AS INT)
                                        FROM    ptype
                                        WHERE   a.typeid = Parid
                                               -- AND deleted = 0
                                      ), 0)
            FROM    ptype a
            IF @@error <> 0 
                GOTO error1
			
            DELETE  FROM bakdlyorder
            WHERE   NOT EXISTS ( SELECT 1
                                 FROM   ptype p
                                 WHERE  sonnum = 0
                                        AND bakdlyorder.ptypeid = p.typeid )
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM bakdlyorderdetail
            WHERE   dlyorder NOT IN ( SELECT    dlyorder
                                      FROM      bakdlyorder )
            IF @@error <> 0 
                GOTO error1	
            DELETE  FROM dlyndxorder
            WHERE   vchcode NOT IN ( SELECT vchcode
                                     FROM   bakdlyorder )
            IF @@error <> 0 
                GOTO error1
		
            DELETE  FROM bakdly
            WHERE   NOT EXISTS ( SELECT 1
                                 FROM   ptype p
                                 WHERE  sonnum = 0
                                        AND bakdly.ptypeid = p.typeid )
                    AND ptypeid <> ''
            IF @@error <> 0 
                GOTO error1	
		
            DELETE  FROM bakdlydetail
            WHERE   dlyorder NOT IN ( SELECT    dlyorder
                                      FROM      bakdly )
            IF @@error <> 0 
                GOTO error1
		
            DELETE  FROM dlyndx
            WHERE   vchcode NOT IN ( SELECT DISTINCT
                                            vchcode
                                     FROM   bakdly
                                     UNION
                                     SELECT DISTINCT
                                            vchcode
                                     FROM   dbo.Dlydata
                                     UNION
                                     SELECT DISTINCT
                                            vchcode
                                     FROM   dbo.DlyA )
            IF @@error <> 0 
                GOTO error1
		
            UPDATE  bakdlyorder
            SET     isover = 1
            FROM    bakdlyorder a
            WHERE   dlyorder NOT IN ( SELECT    od.dlyorder
                                      FROM      bakdlyorderdetail od
                                      WHERE     od.qty > od.toqty ) 
		
            IF @@error <> 0
                OR @@ROWCOUNT < 0 
                GOTO error1
	
            UPDATE  dlyndxorder
            SET     [ifcheck] = '0',
                    [Isover] = 0
            FROM    dlyndxorder a
            WHERE   EXISTS ( SELECT 1
                             FROM   bakdlyorder b
                             WHERE  a.vchcode = b.vchcode
                                    AND ISNULL(isover, 0) = 0 ) 
		    
            IF @@error <> 0
                OR @@ROWCOUNT < 0 
                RETURN -1	
            UPDATE  dlyndxorder
            SET     [ifcheck] = '2',
                    [Isover] = 1
            FROM    dlyndxorder a
            WHERE   NOT EXISTS ( SELECT 1
                                 FROM   bakdlyorder b
                                 WHERE  a.vchcode = b.vchcode
                                        AND ISNULL(isover, 0) = 0 ) 
            IF @@error <> 0
                OR @@ROWCOUNT < 0 
                GOTO error1
	
        END
   --默认删除,总部年结，且所有加盟商都是非单独年结时，才删除商品


-- 判断是否删除停用vip

	-- 此处不处理了，所以置@ifdelVip=0
    SET @ifdelVip = 0	
    IF @ifdelVip = 1 
        BEGIN
            IF EXISTS ( SELECT  1
                        FROM    vipcards
                        WHERE   CardState = 0
                                AND SaveMoney > 0 ) 
                BEGIN
                    DECLARE @vipMoney NUMERIC(24, 10)
                    SELECT  @vipMoney = SUM(savemoney)
                    FROM    vipcards
                    WHERE   CardState = 0
                            AND SaveMoney > 0	
                    UPDATE  atype
                    SET     Total00 = Total00 + @vipMoney
                    WHERE   typeId = '0000500001'
                    UPDATE  atype
                    SET     ttl00 = ttl00 - @vipMoney
                    WHERE   typeId = '0000299999'
                END
            DELETE  FROM dbo.VIPCards
            WHERE   CardState = 0 
        END
	-- 此处不处理了，所以置@ifdelVip=0


-----将VIP储值搬移到期初字段
    IF @Branchid = ''  --总部年结时，才处理VIP,规则改变，见上面
        BEGIN
            UPDATE  Vipcards
            SET     YearIniMoney = savemoney
            WHERE   ( handoutdept = ''
                      OR cardtypeid IN (
                      SELECT    orderid
                      FROM      vipcardtypes
                      WHERE     branchid IN ( SELECT    branchid
                                              FROM      branch
                                              WHERE     selfiniyear = 0 ) )
                    )
            UPDATE  Vipcards
            SET     savemoney = 0
            WHERE   ( handoutdept = ''
                      OR cardtypeid IN (
                      SELECT    orderid
                      FROM      vipcardtypes
                      WHERE     branchid IN ( SELECT    branchid
                                              FROM      branch
                                              WHERE     selfiniyear = 0 ) )
                    )
        END   
    ELSE 
        BEGIN
            UPDATE  Vipcards
            SET     YearIniMoney = savemoney
            WHERE   cardtypeid IN ( SELECT  orderid
                                    FROM    vipcardtypes
                                    WHERE   branchid = @branchid )
            UPDATE  Vipcards
            SET     savemoney = 0
            WHERE   cardtypeid IN ( SELECT  orderid
                                    FROM    vipcardtypes
                                    WHERE   branchid = @branchid )
        END
-----将VIP储值搬移到期初字段


    IF @Branchid = '' 
        BEGIN
            UPDATE  Branch
            SET     Iniover = 0
            WHERE   selfiniyear = 0
        END
    ELSE 
        BEGIN
            UPDATE  Branch
            SET     Iniover = 0
            WHERE   Branchid = @Branchid
        END


--总部年结时清除，加盟不清除,去掉（只清未开账状态机构的虚拟库存）
   -- 清空虚拟库存

    CREATE TABLE #stock ( typeid VARCHAR(50) )
    IF @branchid = '' 
        BEGIN
            INSERT  INTO #stock
                    SELECT  typeid
                    FROM    stock
                    WHERE   branchid IN ( SELECT    branchid
                                          FROM      branch
                                          WHERE     iniover = 0 )
        END
    ELSE 
        BEGIN
            INSERT  INTO #stock
                    SELECT  typeid
                    FROM    stock
                    WHERE   branchid = @branchid
        END

--IF @Branchid =''
    BEGIN   
        DELETE  FROM GoodsVirtual
        WHERE   ktypeid IN ( SELECT typeid
                             FROM   #stock )
        IF @@error <> 0 
            GOTO error1   
    END

    DROP TABLE #stock
--总部年结时清除，加盟不清除,去掉（只清未开账状态机构的虚拟库存）



 /***************************************
系统重建和年结存 关于 清除审核的相关操作
***************************************/
--1.
    DELETE  FROM AuditingFlowSet
    WHERE   IfUse = 0 --审核主表(删除已经过期的审核流程)
--2.
    IF @branchid = '' 
        BEGIN
	--一般单据
            DELETE  FROM AuditingBill
            WHERE   billindextype <> 0
                    AND Vchcode IN (
                    SELECT  vchcode
                    FROM    dlyndx
                    WHERE   ( branchid2 = ''
                              AND branchid IN ( SELECT  branchid
                                                FROM    branch
                                                WHERE   selfiniyear = 0 )
                            )
                            OR ( branchid2 <> ''
                                 AND branchid2 IN ( SELECT  branchid
                                                    FROM    branch
                                                    WHERE   selfiniyear = 0 )
                               ) ) --审核记录表(存放单据审核的最终审核状态和审核的历史记录）
	--订单
            DELETE  FROM AuditingBill
            WHERE   billindextype = 0
                    AND Vchcode IN (
                    SELECT  vchcode
                    FROM    dlyndxorder
                    WHERE   ( branchid2 = ''
                              AND branchid IN ( SELECT  branchid
                                                FROM    branch
                                                WHERE   selfiniyear = 0 )
                            )
                            OR ( branchid2 <> ''
                                 AND branchid2 IN ( SELECT  branchid
                                                    FROM    branch
                                                    WHERE   selfiniyear = 0 )
                               ) ) --审核记录表(存放单据审核的最终审核状态和审核的历史记录）
	--3.(如果有保留 未完成的订单 配置)
            UPDATE  DlyNdxOrder
            SET     IfAudit = 2
            WHERE   IfAudit = 1
                    AND Vchcode IN (
                    SELECT  vchcode
                    FROM    dlyndxorder
                    WHERE   ( branchid2 = ''
                              AND branchid IN ( SELECT  branchid
                                                FROM    branch
                                                WHERE   selfiniyear = 0 )
                            )
                            OR ( branchid2 <> ''
                                 AND branchid2 IN ( SELECT  branchid
                                                    FROM    branch
                                                    WHERE   selfiniyear = 0 )
                               ) )--审核通过的订单--》改成 无需审核的订单
            UPDATE  DlyNdxOrder
            SET     IfAudit = -2
            WHERE   IfAudit IN ( 0, -1 )
                    AND Vchcode IN (
                    SELECT  vchcode
                    FROM    dlyndxorder
                    WHERE   ( branchid2 = ''
                              AND branchid IN ( SELECT  branchid
                                                FROM    branch
                                                WHERE   selfiniyear = 0 )
                            )
                            OR ( branchid2 <> ''
                                 AND branchid2 IN ( SELECT  branchid
                                                    FROM    branch
                                                    WHERE   selfiniyear = 0 )
                               ) )--待审核和审核不通过的订单--》改成 满足审核不提交
        END
    ELSE 
        BEGIN
	--一般单据
            DELETE  FROM AuditingBill
            WHERE   billindextype <> 0
                    AND Vchcode IN ( SELECT vchcode
                                     FROM   dlyndx
                                     WHERE  ( branchid2 = ''
                                              AND branchid = @branchid
                                            )
                                            OR ( branchid2 <> ''
                                                 AND branchid2 = @branchid
                                               ) ) --审核记录表(存放单据审核的最终审核状态和审核的历史记录）
	--订单
            DELETE  FROM AuditingBill
            WHERE   billindextype = 0
                    AND Vchcode IN ( SELECT vchcode
                                     FROM   dlyndxorder
                                     WHERE  ( branchid2 = ''
                                              AND branchid = @branchid
                                            )
                                            OR ( branchid2 <> ''
                                                 AND branchid2 = @branchid
                                               ) ) --审核记录表(存放单据审核的最终审核状态和审核的历史记录）
	--3.(如果有保留 未完成的订单 配置)
            UPDATE  DlyNdxOrder
            SET     IfAudit = 2
            WHERE   IfAudit = 1
                    AND Vchcode IN ( SELECT vchcode
                                     FROM   dlyndxorder
                                     WHERE  ( branchid2 = ''
                                              AND branchid = @branchid
                                            )
                                            OR ( branchid2 <> ''
                                                 AND branchid2 = @branchid
                                               ) )--审核通过的订单--》改成 无需审核的订单
            UPDATE  DlyNdxOrder
            SET     IfAudit = -2
            WHERE   IfAudit IN ( 0, -1 )
                    AND Vchcode IN ( SELECT vchcode
                                     FROM   dlyndxorder
                                     WHERE  ( branchid2 = ''
                                              AND branchid = @branchid
                                            )
                                            OR ( branchid2 <> ''
                                                 AND branchid2 = @branchid
                                               ) )--待审核和审核不通过的订单--》改成 满足审核不提交
        END


    DELETE  FROM PtypeUniqueCode
    WHERE   vchcode NOT IN ( SELECT vchcode
                             FROM   dlyndx )  --商品唯一码记录表
    DELETE  FROM PtypeUniqueCheck
    WHERE   vchcode NOT IN ( SELECT vchcode
                             FROM   dlyndx )  --商品唯一码校验表
                             
    --清除商品积分明细(主表没得的清了）                           
    DELETE FROM  VipIntegralPtypeDetail WHERE nOrder NOT IN (   SELECT nOrder FROM VipIntegralDetail)

	--删除没有主表的dlyNdxB DlyNdxOrderB记录
	delete from dlyNdxB where not exists (select 1 from dlyndx d where d.vchcode=vchcode)
	delete from DlyNdxOrderB where not exists (select 1 from DlyNdxOrder d where d.vchcode=vchcode)

    COMMIT TRAN YearClose
    RETURN 0
    error1:
    BEGIN
        ROLLBACK TRAN YearClose
        RETURN -1		
    END
    error10:
    CLOSE ini_cursor
    DEALLOCATE ini_cursor
    ROLLBACK TRAN YearClose
    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].[GetShortcutMenuList]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GetShortcutMenuList]
GO

-- ==================================================================
-- 功能说明：获取用户常用菜单列表,若用户未定义则通过操作日志记录获取
-- ==================================================================
CREATE  PROCEDURE GetShortcutMenuList
    (
      @EtypeId VARCHAR(50) ,	--操作员ID
      @OnlySet INT = 0			--只获取用户自定义项，0：否 1：是
    )
AS 

	DECLARE @isEnableDZT VARCHAR(2),@isEnabelPOS VARCHAR(2),@mpo VARCHAR(2)
	SELECT @isEnabelPOS = SubValue FROM dbo.SysData WHERE SubName = 'usepos'
    SELECT @isEnableDZT = SubValue FROM dbo.SysData WHERE SubName = 'BoolDZT'
    SELECT @mpo = SubValue FROM dbo.SysData WHERE SubName = 'mposetting'
    IF @OnlySet = 1 
        BEGIN
            SELECT  sm.EtypeId ,
                    sm.ModuleName ,
                    sm.offset ,
                    sm.OrderId
            FROM    dbo.ShortcutMenu sm
            WHERE   sm.EtypeId = @EtypeId
            AND NOT EXISTS(SELECT 1 FROM dbo.WebMenu wm WHERE wm.offset =sm.offset AND (ModuleID LIKE '15%' OR ModuleID LIKE '0409%' OR ModuleID LIKE '17%'))
            UNION ALL
            SELECT  sm.EtypeId ,
                    sm.ModuleName ,
                    sm.offset,
                    sm.OrderId
            FROM    dbo.ShortcutMenu sm
            WHERE   sm.EtypeId = @EtypeId
            AND EXISTS(SELECT 1 FROM dbo.WebMenu wm WHERE wm.offset =sm.offset AND ((ModuleID LIKE CASE WHEN @isEnableDZT = '1' THEN '15%' ELSE 'abcd' END)OR (ModuleID LIKE CASE WHEN @mpo = '1' THEN '17%' ELSE 'abcd' END) OR (ModuleID LIKE CASE WHEN @isEnabelPOS = '1' THEN '0409%' ELSE 'abcd' END)))
        END
    ELSE
        IF EXISTS ( SELECT  1
                    FROM    ShortcutMenu
                    WHERE   EtypeId = @EtypeId ) 
            BEGIN
           SELECT  sm.EtypeId ,
                    sm.ModuleName ,
                    sm.offset ,
                    sm.OrderId
            FROM    dbo.ShortcutMenu sm
            WHERE   sm.EtypeId = @EtypeId
            AND NOT EXISTS(SELECT 1 FROM dbo.WebMenu wm WHERE wm.offset =sm.offset AND (ModuleID LIKE '15%' OR ModuleID LIKE '17%' OR ModuleID LIKE '0409%'))
            UNION ALL
            SELECT  sm.EtypeId ,
                    sm.ModuleName ,
                    sm.offset,
                    sm.OrderId
            FROM    dbo.ShortcutMenu sm
            WHERE   sm.EtypeId = @EtypeId
            AND EXISTS(SELECT 1 FROM dbo.WebMenu wm WHERE wm.offset =sm.offset AND ((ModuleID LIKE CASE WHEN @isEnableDZT = '1' THEN '15%' ELSE 'abcd' END) OR (ModuleID LIKE CASE WHEN @mpo = '1' THEN '17%' ELSE 'abcd' END) OR (ModuleID LIKE CASE WHEN @isEnabelPOS = '1' THEN '0409%' ELSE 'abcd' END)))
            END
        ELSE 
            BEGIN
				SELECT TOP 10 
				tmp.EtypeId,tmp.ModuleName,tmp.offset,tmp.OrderId
				FROM (
						SELECT TOP 10
								a.EtypeId ,
								CASE WHEN a.offset IN (172,171,169,178,34,162,163,173,176,31,291,278,233,289,36,174,179,180,32,290,167,170,285,168,177,35,164,166,165,263,175,33) THEN c.ModuleName+'--'+b.ModuleName ELSE b.ModuleName END AS ModuleName ,
								b.offset ,
								COUNT(1) AS OrderId
						FROM    SysLog a
								INNER JOIN WebMenu b ON b.offset = a.offset LEFT JOIN WebMenu c ON c.ModuleID = LEFT(b.ModuleID,LEN(b.ModuleID)-2)
						WHERE   a.EtypeId = @EtypeId
						AND b.ModuleID NOT LIKE '15%' 
						AND b.ModuleID NOT LIKE '0409%'
						AND b.ModuleID NOT LIKE '17%'
						GROUP BY a.EtypeId ,
								CASE WHEN a.offset IN (172,171,169,178,34,162,163,173,176,31,291,278,233,289,36,174,179,180,32,290,167,170,285,168,177,35,164,166,165,263,175,33) THEN c.ModuleName+'--'+b.ModuleName ELSE b.ModuleName END ,
								b.offset
						UNION ALL
						SELECT TOP 10
								a.EtypeId ,
								CASE WHEN a.offset IN (172,171,169,178,34,162,163,173,176,31,291,278,233,289,36,174,179,180,32,290,167,170,285,168,177,35,164,166,165,263,175,33) THEN c.ModuleName+'--'+b.ModuleName ELSE b.ModuleName END AS ModuleName ,
								b.offset ,
								COUNT(1) AS OrderId
						FROM    SysLog a
								INNER JOIN WebMenu b ON b.offset = a.offset LEFT JOIN WebMenu c ON c.ModuleID = LEFT(b.ModuleID,LEN(b.ModuleID)-2)
						WHERE   a.EtypeId = @EtypeId
						AND ( (b.ModuleID LIKE CASE WHEN @isEnableDZT = '1' THEN '15%' ELSE 'abcd' END) 
							  OR
							  (b.ModuleID LIKE CASE WHEN @isEnabelPOS = '1' THEN '0409%' ELSE 'abcd' END)
							  OR
							  (b.ModuleID LIKE CASE WHEN @mpo = '1' THEN '17%' ELSE 'abcd' END)
							 )
						GROUP BY a.EtypeId ,
								CASE WHEN a.offset IN (172,171,169,178,34,162,163,173,176,31,291,278,233,289,36,174,179,180,32,290,167,170,285,168,177,35,164,166,165,263,175,33) THEN c.ModuleName+'--'+b.ModuleName ELSE b.ModuleName END ,
								b.offset
                   ) tmp
                   ORDER BY tmp.OrderId DESC
            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].[FZSetSYSsz]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZSetSYSsz]
GO


--  ********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：F_S_SetSYSsz                                          
--  ||   过程功能：系统设置－－系统配置  
--  ||=========================================================================================  
--  ||   参数说明：  参数名称         类型            意义                     输入输出  
--  ||            -----------------------------------------------------------------------------  
--  ||        @szValue*   varchar(100)                 写入对应的单位设置值  
--  ||=========================================================================================     
--  ||   返回值：         值                                     说明  
--  ||       ----------------------------------------------------------------------------------------  
--  ||                    0                                 执行成功  
--  ||                  －1                               执行失败  
--  ||==========================================================================================  
CREATE   PROCEDURE FZSetSYSsz
    (
      @szValue1 VARCHAR(100),--是否使用同一成本算法：－1不使用统一成本算法，0:加权平均法，1:先进先出法，2:后进先出法，3:手工指定法  
      @szValue2 VARCHAR(100),--统一折扣和税率：0：统一零售价多折扣，1：多价格管理方式  
      @szValue3 VARCHAR(100),--业务单据录入行数  
      @szValue4 VARCHAR(100),--系统自动备份天数  
      @szValue5 VARCHAR(100),--数量小数位数配置  
      @szValue6 VARCHAR(100),--单价小数位数配置  
      @szValue7 VARCHAR(100),--金额小数位数配置  
      @szValue8 VARCHAR(100),--税率小数位数配置  
      @szValue9 VARCHAR(100),--折扣小数位数配置  
      @szValue10 VARCHAR(1),
      @szValue11 VARCHAR(1),--数量启用小数  
      @szValue12 VARCHAR(1),--扣率启用小数  
      @szValue13 VARCHAR(1),  --pos结算配置	     
      @szValue14 VARCHAR(100),--商品唯一码小数位数设置
      @szValue15 VARCHAR(100),--加盟商配货单权限设置
      @szValue16 VARCHAR(100),--内部配货单权限设置
      @szValue17 VARCHAR(100),--是否启用POS管理
      @szValue18 VARCHAR(1),--是否启用唯一码
      @szValue19 VARCHAR(1),--唯一码管理方式
      @szValue20 VARCHAR(1),--是否启用退货价跟踪
      @szValue21 VARCHAR(1),--商品录入方式选择:0=启用配码，1=启用双单位
      @szValue22 VARCHAR(100),--配货申请单权限设置
      @szValue23 VARCHAR(100),--是否启用店账通
      @szValue24 VARCHAR(100),--OA消息间隔
      @szValue25 VARCHAR(100),--指定用户数
      @szValue26 VARCHAR(100),-- 产品名称
      @szValue27 VARCHAR(100),-- 是否启用订货会
      @modifydig INT = 0 OUT               
    )
AS 
    DECLARE @re INT
    SET @re = -1
    BEGIN TRAN   
    UPDATE  [sysdata]
    SET     subvalue = @szValue1
    WHERE   subname = 'unitedisctax'  
		--由启用小数改到未启用小数
    IF @szValue11 = '0'
        AND EXISTS ( SELECT *
                     FROM   Sysdata
                     WHERE  subname = 'IfDecimalQty'
                            AND SubValue = '1' ) 
        BEGIN
            SET @modifydig = 1
            IF EXISTS ( SELECT TOP 1
                                1
                        FROM    GoodsstockDetail )
                OR EXISTS ( SELECT TOP 1
                                    1
                            FROM    iniGoodsDetail )
                OR EXISTS ( SELECT TOP 1
                                    1
                            FROM    bakdly ) 
                BEGIN
                    SET @re = -2
                    GOTO Error00
                END
        END
		--数量由不启用小数改到启用小数
    IF @szValue11 = '1'
        AND EXISTS ( SELECT *
                     FROM   Sysdata
                     WHERE  subname = 'IfDecimalQty'
                            AND SubValue = '0' ) 
        BEGIN
            SET @modifydig = 2
        END

    IF @szValue12 = '0'
        AND EXISTS ( SELECT *
                     FROM   Sysdata
                     WHERE  subname = 'IfDecimalDiscount'
                            AND SubValue = '1' ) 
        BEGIN
            SET @modifydig = 3
            IF EXISTS ( SELECT TOP 1
                                1
                        FROM    GoodsstockDetail )
                OR EXISTS ( SELECT TOP 1
                                    1
                            FROM    iniGoodsDetail )
                OR EXISTS ( SELECT TOP 1
                                    1
                            FROM    bakdly )
                OR EXISTS ( SELECT TOP 1
                                    1
                            FROM    PtypePrice ) 
                BEGIN
                    SET @re = -3
                    GOTO Error00
                END
        END
		--折扣由不启用小数改到启用小数
    IF @szValue12 = '1'
        AND EXISTS ( SELECT *
                     FROM   Sysdata
                     WHERE  subname = 'IfDecimalDiscount'
                            AND SubValue = '0' ) 
        BEGIN
            SET @modifydig = 4
        END

    UPDATE  [sysdata]
    SET     subvalue = @szValue2
    WHERE   subname = 'usesamecostmode'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue3
    WHERE   subname = 'billrow'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue4
    WHERE   subname = 'autobakupdays'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue5
    WHERE   subname = 'DecimalQty'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue6
    WHERE   subname = 'DecimalPrice'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue7
    WHERE   subname = 'DecimalTotal'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue8
    WHERE   subname = 'DecimalTaxRate'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue9
    WHERE   subname = 'DecimalDiscount'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue10
    WHERE   subname = 'CanPrintScreen'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue11
    WHERE   subname = 'IfDecimalQty'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue12
    WHERE   subname = 'IfDecimalDiscount'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue13
    WHERE   subname = 'posPayConfig' 
    UPDATE  [sysdata]
    SET     subvalue = @szValue14
    WHERE   subname = 'PtypeUniqueSet' 
    UPDATE  [sysdata]
    SET     subvalue = @szValue15
    WHERE   subname = 'JMSLimit'
    UPDATE  [sysdata]
    SET     subvalue = @szValue16
    WHERE   subname = 'NBPHLimit'
    UPDATE  [sysdata]
    SET     subvalue = @szValue17
    WHERE   subname = 'usepos'
    UPDATE  [sysdata]
    SET     subvalue = @szValue18
    WHERE   subname = 'useUnique'
    UPDATE  [sysdata]
    SET     subvalue = @szValue19
    WHERE   subname = 'UniqueManageType'
    UPDATE  [sysdata]
    SET     subvalue = @szValue20
    WHERE   subname = 'tailBackPrice'
    UPDATE  [sysdata]
    SET     subvalue = @szValue21
    WHERE   subname = 'goodsInputStyle'
    UPDATE  [sysdata]
    SET     subvalue = @szValue22
    WHERE   subname = 'PHSQLimit'
    UPDATE  [sysdata] 
    SET     subvalue = @szValue23
    WHERE   subname = 'BoolDZT'
    --OA消息间隔
    UPDATE  [sysdata] 
    SET     subvalue = @szValue24
    WHERE   subname = 'OaMessageTime'
    --指定用户数
    UPDATE  [sysdata] 
    SET     subvalue = @szValue25
    WHERE   subname = 'UserNumber'
    
    --是否启用订货会
    UPDATE  [sysdata] 
    SET     subvalue = @szValue27
    WHERE   subname = 'mposetting'
    
    --产品名称
    UPDATE  [sysdata] 
    SET     subvalue = @szValue26
    WHERE   subname = 'CPName'
    
		--改变系统小数位配置
    IF @szValue11 = '1' 
        UPDATE  numberconfig
        SET     digits = 2
        WHERE   typename = 'qty'
    ELSE 
        UPDATE  numberconfig
        SET     digits = 0
        WHERE   typename = 'qty'

    IF @szValue12 = '1' 
        UPDATE  numberconfig
        SET     digits = 2
        WHERE   typename = 'discount'
    ELSE 
        UPDATE  numberconfig
        SET     digits = 0
        WHERE   typename = 'discount'


    IF @@Error <> 0 
        GOTO Error00  
         
    GOTO Success00  
    Success00:  
    COMMIT TRAN   
    RETURN 0  
    Error00:  
    ROLLBACK TRAN   
    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].[FZGetSYS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FZGetSYS]
GO


--  ********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：F_S_GetSYSsz                                          
--  ||   过程功能：系统设置－－系统配置（读）  
--  ||=========================================================================================  
--  ||   参数说明：  参数名称         类型            意义                     输入输出  
--  ||            -----------------------------------------------------------------------------  
--  ||        @szValue*   varchar(100)                 写入对应的单位设置值  
--  ||=========================================================================================     
--  ||   返回值：         值                                     说明  
--  ||       ----------------------------------------------------------------------------------------  
--  ||                    0                                 执行成功  
--  ||                  －1                               执行失败  
--  ||==========================================================================================  
CREATE  PROCEDURE FZGetSYS  
(            @subValue1   varchar(100) output,--是否使用同一成本算法：－1不使用统一成本算法，0:加权平均法，1:先进先出法，2:后进先出法，3:手工指定法  
             @subValue2   varchar(100) output,--设定价格管理方式0：统一零售价多折扣，1：多价格管理方式  
             @subValue3   varchar(100) output,--业务单据录入行数  
             @subValue4   varchar(100) output,--系统自动备份天数  
             @subValue5   varchar(100) output,--数量小数位数配置  
             @subValue6  varchar(100) output,--单价小数位数配置  
             @subValue7   varchar(100) output,--金额小数位数配置  
             @subValue8 varchar(100) output,--税率小数位数配置  
             @subValue9 varchar(100) output,--折扣小数位数配置  
             @subValue10 varchar(1)  output,  --是否截屏  
             @subValue11 varchar(100) output,--  
             @subValue12 varchar(100) output,--  
             @subValue13 varchar(100) output,--  
             @subValue14 varchar(1)  output,  --  
             @subValue15 varchar(100) output,--  
             @subValue16 varchar(100) output,--  
             @subValue17 varchar(100) output,  
             @subValue18 varchar(1) output,--数量启用小数  
             @subValue19 varchar(1) output,--扣率启用小数  
             @subvalue20 varchar(1) output,  
             @subvalue21 varchar(100) output, --商品唯一码位数
             @subvalue22 varchar(100) output, --加盟商配货单机构权限设置
             @subvalue23 varchar(100) output, --内部配货单机构权限设置 
             @subvalue24 varchar(100) OUTPUT,  --启用POS
             @subvalue25 varchar(1) OUTPUT,  --是否启用唯一码
             @subvalue26 varchar(1) OUTPUT,  --唯一码管理方式
             @subvalue27 varchar(1) OUTPUT,  --是否启用退货价跟踪
             @subvalue28 varchar(1) OUTPUT,  --商品录入方式选择:0=启用配码，1=启用双单位
             @subvalue29 varchar(100) output,  --配货申请单机构权限设置
             @subvalue30 varchar(100) OUTPUT,  --启用店账通
             @subvalue31 varchar(100) output  --启用订货会
)  
AS  
selectSysdata:  
       select @subvalue1 =(select subvalue From [sysdata]  Where subname='usesamecostmode')  
       if @subvalue1<>0 and exists( select 1 from syscon where  [stats]=1 and [order]=106)  
       Begin  
     update syscon set [stats]=0 where [order]=106  
       end  
       select @subvalue2 =(select subvalue From [sysdata]  Where subname='unitedisctax')  
       select @subvalue3 =(select subvalue From [sysdata]  Where subname='billrow')  
       select @subvalue4 =(select subvalue From [sysdata]  Where subname='autobakupdays')  
       select @subvalue5 =(select subvalue From [sysdata]  Where subname='DecimalQty')  
       select @subvalue6 =(select subvalue From [sysdata]  Where subname='DecimalPrice')  
       select @subvalue7 =(select subvalue From [sysdata]  Where subname='DecimalTotal')  
       select @subvalue8 =(select subvalue From [sysdata]  Where subname='DecimalTaxRate')  
       select @subvalue9 =(select subvalue From [sysdata]  Where subname='DecimalDiscount')  
       select @subvalue10 =(select subvalue From [sysdata]  Where subname='CanPrintScreen')  
       select @subvalue11 =(select subvalue From [sysdata]  Where subname='RETAIL_BTYPE_ID')  
       select @subvalue12 =(select subvalue From [sysdata]  Where subname='RETAIL_KTYPE_ID')  
       select @subvalue13 =(select subvalue From [sysdata]  Where subname='RETAIL_ATYPE_ID')  
       select @subvalue14 =(select subvalue From [sysdata]  Where subname='CashAsBillMoney')  
       select @subvalue15 =(select subvalue From [sysdata]  Where subname='RETAIL_BTYPE_NAME')  
       select @subvalue16 =(select subvalue From [sysdata]  Where subname='RETAIL_KTYPE_NAME')  
       select @subvalue17 =(select subvalue From [sysdata]  Where subname='RETAIL_ATYPE_NAME')  
       select @subvalue18 =(select subvalue From [sysdata]  Where subname='IfDecimalQty')  
       select @subvalue19 =(select subvalue From [sysdata]  Where subname='IfDecimalDiscount')  
       select @subvalue20 =(select subvalue From [sysdata]  Where subname='posPayConfig')  
       select @subvalue21 =(select subvalue From [sysdata]  Where subname='PtypeUniqueSet')  
       select @subvalue22 =(select subvalue from [sysdata] where subname='JMSLimit')
       select @subvalue23 =(select subvalue from [sysdata] where subname='NBPHLimit')
       select @subvalue24 =(select subvalue from [sysdata] where subname='usepos')
       select @subvalue25 =(select subvalue from [sysdata] where subname='useUnique')
       select @subvalue26 =(select subvalue from [sysdata] where subname='UniqueManageType')
       select @subvalue27 =(select subvalue from [sysdata] where subname='tailBackPrice')
       select @subvalue28 =(select subvalue from [sysdata] where subname='goodsInputStyle')
       select @subvalue29 =(select subvalue from [sysdata] where subname='PHSQLimit')
       select @subvalue30 =(select subvalue from [sysdata] where subname='BoolDZT')
       select @subvalue31 =(select subvalue from [sysdata] where subname='mposetting')
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FN_gp_CreateMenuItemForASP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FN_gp_CreateMenuItemForASP]
GO
-- ========================================================================
-- 功能说明：		创建菜单项 ( 同时匹配软件狗版本号 )
-- 最后修改作者：	卢   春
-- 最后修改时间：	2003-07-31

-- 修改描述:增加在扣率格式下的VIP菜单项目
-- 修改作者:谢吉康
-- 修改日期:2004-06-04
-- 修改标记:#01
-- ========================================================================
CREATE                           PROCEDURE FN_gp_CreateMenuItemForASP
(
	@chvOperator	VARCHAR(100),	-- 操作员 ID 值
	@ParentID	varchar(10),			-- 父节点 ID 值
	@intValue		INT				-- 软件狗 DLL 通过 ASP 控件返回的加密字串
)
--@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	********

DECLARE @usepos char(1)
SET @usepos='0'
select @usepos=subvalue from sysdata where subname='usepos'
DECLARE @BoolDZT CHAR(1)
SET @BoolDZT='0'
SELECT @BoolDZT=subvalue FROM SysData WHERE SubName='BoolDZT'
DECLARE @mpo CHAR(1)
SET @mpo='0'
SELECT @mpo=subvalue FROM SysData WHERE SubName='mposetting'

	IF @chvOperator<>'00000'
		IF NOT EXISTS(
		SELECT	1
		FROM	LoginUser
		WHERE	ETypeID = @chvOperator
	)
		RETURN 1	-- 操作员不存在

declare @PtypeUniqueSet varchar(10) --唯一码菜单
SET @PtypeUniqueSet='051008'
IF EXISTS(select * from sysdata where subname='useUnique' and subvalue>=1)
	SET @PtypeUniqueSet=''



declare @ifjm int
SET @ifjm=0
if exists(select  * from employee WHERE typeid=@chvOperator and left(branchid,5)='00004') --是否加盟操作员
BEGIN
	SET @ifjm=1
END
IF @chvOperator='00000'
select 
	Distinct 
	m.moduleID as MenuID,
	left(m.moduleID,len(m.moduleID)-2) as parentid,
	m.moduleName as caption,
	m.moduleID as [name],
	m.offset as offset,
	(Select Count(*) From WebMenu m1 Where m1.ModuleId like m.ModuleId + '__') as IsSubMenu,
	'' as img,
	moduleOrder 
from WebMenu m 
where ismenu=1 and moduleid<>'' and LEFT(m.moduleID,len(m.moduleid)-2)=@ParentID
and moduleid<>@PtypeUniqueSet
AND left(moduleid,4)<>(case when @usepos='1' then '' else '0409' end)
AND left(moduleid,4)<>(case when @BoolDZT='1' then '' else '15' end)
AND left(moduleid,4)<>(case when @mpo='1' then '' else '17' end)
order by m.moduleOrder
ELSE
BEGIN
	IF @ifjm =1
		select 
			Distinct 
			m.moduleID as MenuID,
			left(m.moduleID,len(m.moduleID)-2) as parentid,
			m.moduleName as caption,
			m.moduleID as [name],
			m.offset as offset,
			(Select Count(*) From WebMenu m1 Where m1.ModuleId like m.ModuleId + '__') as IsSubMenu,
			'' as img,
			moduleOrder 
		from WebMenu m 
		where ismenu=1 and  moduleid<>'' and  LEFT(m.moduleID,len(m.moduleid)-2)=@ParentID
		and ifjm=1
		and moduleid<>@PtypeUniqueSet
		AND Exists(select 1 from employeepower e where e.etypeid=@chvOperator AND m.moduleid=e.moduleid or @chvOperator='00000' or m.ispower=0)
		AND left(moduleid,4)<>(case when @usepos='1' then '' else '0409' end)
		AND left(moduleid,4)<>(case when @BoolDZT='1' then '' else '15' end)
		AND left(moduleid,4)<>(case when @mpo='1' then '' else '17' end)
		order by m.moduleOrder
	ELSE
		select 
			Distinct 
			m.moduleID as MenuID,
			left(m.moduleID,len(m.moduleID)-2) as parentid,
			m.moduleName as caption,
			m.moduleID as [name],
			m.offset as offset,
			(Select Count(*) From WebMenu m1 Where m1.ModuleId like m.ModuleId + '__') as IsSubMenu,
			'' as img,
			moduleOrder 
		from WebMenu m 
		where ismenu=1 and  moduleid<>'' and  LEFT(m.moduleID,len(m.moduleid)-2)=@ParentID
		and moduleid<>@PtypeUniqueSet
		AND Exists(select 1 from employeepower e where e.etypeid=@chvOperator AND m.moduleid=e.moduleid or @chvOperator='00000' or m.ispower=0)
		AND left(moduleid,4)<>(case when @usepos='1' then '' else '0409' end)
		AND left(moduleid,4)<>(case when @BoolDZT='1' then '' else '15' end)
		AND left(moduleid,4)<>(case when @mpo='1' then '' else '17' end)
		order by m.moduleOrder
END


RETURN 0
/*
DECLARE @btypeid VARCHAR(50),@sysid CHAR(1),@lim VARCHAR(2000)
SELECT @sysid=SysID,@btypeid=BtypeID,@lim=Lim FROM Loginuser WHERE etypeid=@chvOperator


DECLARE @sql VARCHAR(8000),@lx INT,@start INT
DECLARE @sqlm VARCHAR(8000),@sqln VARCHAR(8000),@sqlo VARCHAR(8000)
DECLARE @checkSerial INT

-----检查是否可使用序列号  吴德水 2003-05-22-----
IF EXISTS(SELECT SubNo FROM sysdata WHERE SubName='Edition' AND (SubValue=2 OR SubValue=5))
	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))
		SET @checkSerial=1
	ELSE
		SET @checkSerial=0
----------------------------------------------------------------------
SELECT @sqln=''
SELECT @sqlo=''

-- 谢吉康  2005-1-18 判断是否采用了“采用分支机构预设售价管理”
DECLARE @sqlG varchar(1000)
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)'
	ELSE
		SELECT @sqlm=' 1=1'
ELSE
	BEGIN
		IF @checkSerial=0
			SELECT @sqlm=' SUBSTRING('''+@Lim+''',offset,1)=''1'' AND offset NOT IN (226,227,228)'
		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(1000)
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,69015,751,1205) AND ParentID NOT IN (11003000,5095,5096,69015,751,1205)'

-- 基础版不享受 “商品近效期查询” 菜单项
DECLARE @chvSQLSP varchar(200)
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 = ' MenuID NOT IN (765)'
ELSE
	SET @chvSQLSP = ' 1=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)'

-- V419暂时关闭维修菜单 谢吉康 2009-8-21
--SET @chvSQLSP = @chvSQLSP + ' AND MenuID NOT IN (11003000,11003010,11003030,11003020,11003040,11003050)'

-- chen_qihua 2004-12-20 单据自定义编号 菜单不显示(如果没有选中此选项) 创建新表
CREATE TABLE #WebMenu 
(
	MenuID 		int,
	ParentID 	int,
	Caption 	varchar(50),
	[Name] 		varchar(50),
	IsSubMenu 	bit,
	img 		varchar(100)

)


--SELECT @sql='SELECT  menuid,parentid,caption,NAME,issubmenu,img FROM webmenu WHERE sysid=0 AND ('+@sqlm+@sqln+@sqlo+' ) AND ('+@sqlG+') AND ParentID='+CAST(@ParentID AS VARCHAR(10) ) +' ORDER BY tabord'  #01
IF @ParentID='1100' --系统管理，开账向导
	SELECT @sql='INSERT INTO #WebMenu SELECT  menuid,parentid,caption,NAME,issubmenu,img  FROM webmenu WHERE sysid=0 AND ('+@sqlm+@sqln+@sqlo+' ) AND ('+@sqlG+') AND (' + @chvSQLDiff + ') AND ('+@chvSQLSP+') AND ParentID='+CAST(@ParentID AS VARCHAR(10) ) +' OR Caption =''开账向导'' ORDER BY tabord'
ELSE
	SELECT @sql='INSERT INTO #WebMenu SELECT  menuid,parentid,caption,NAME,issubmenu,img  FROM webmenu WHERE sysid=0 AND ('+@sqlm+@sqln+@sqlo+' ) AND ('+@sqlG+') AND (' + @chvSQLDiff + ') AND ('+@chvSQLSP+') AND ParentID='+CAST(@ParentID AS VARCHAR(10) ) +' ORDER BY tabord'
----------------------------------------------------------------------
--PRINT @sql
EXEC(@sql)

-- 删除单据自定义编号的菜单
IF NOT EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName ='BillCodeConfig' AND Value='1')
	DELETE FROM #WebMenu WHERE Name ='LIMIT_BillCode_Config'

--IF EXISTS(SELECT TOP 1 1 FROM UserConfig WHERE ConfigName = 'IfTopMenu' AND Value = 1)
--	SELECT * FROM #WebMenu WHERE MenuId NOT IN (1220,1240)
--ELSE
	SELECT * FROM #WebMenu

DROP TABLE #WebMenu
*/
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/******************************************20130620********************************************/
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZInsertColorSize]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
  DROP PROCEDURE [dbo].[FZInsertColorSize]
GO




/*写入商品颜色或尺码的基本信息  
       0     执行成功  
       －1 执行失败  
       －2  有相同名称的颜色、尺码存在  
    - 3  有相同编码的颜色、尺码存在  
*/  
CREATE  PROCEDURE FZInsertColorSize
  (
    @tablename VARCHAR(1) ,         --输入的表名'C:颜色表，S：为尺码表'  
    @name VARCHAR(30) ,        --设置颜色名称  
    @barcode VARCHAR(230) ,        --相应条码  
    @remark VARCHAR(100) ,       --用户说明  
    @iMode VARCHAR(1) ,         --操作方式  增加A、修改M、删除D
    @csid INT                 --旧的颜色、尺码   
    
  )
AS 
/*
alter by hww 2011年8月17日15:14:04
在删除尺码时，增加对配码包的检查，如果被配码包占用，则不能删除
*/
  DECLARE @colorgroupid INT ,
    @sizegroupid VARCHAR(30) ,
    @oldbar VARCHAR(30)  
  DECLARE @oldBcon VARCHAR(30) ,
    @ptypeid VARCHAR(50) ,
    @formatid VARCHAR(10) ,
    @oobarcode VARCHAR(30)   
  DECLARE @oldCGid INT ,
    @oldSGid INT ,
    @cid INT    
  DECLARE @colorid INT ,
    @cbar VARCHAR(10) ,
    @sieeid INT ,
    @sbar VARCHAR(10) ,
    @bar VARCHAR(50)   
  DECLARE @Stats1 INT  
  DECLARE @Stats2 INT  
  SELECT  @Stats1 = stats
  FROM    syscon
  WHERE   [order] = 81  
  SELECT  @Stats2 = stats
  FROM    syscon
  WHERE   [order] = 82  
  DECLARE @UpdateTag INT
  IF @tablename = 'C' 
    BEGIN  

      IF @iMode = 'A' 
        BEGIN  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   [name] = @name
                              AND @Stats1 = 1 ) 
            GOTO error100 --不允许名称相同  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   [barcode] = @barcode
                              AND @Stats2 = 1 ) 
            GOTO error101--不允许编码相同  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [name] = @name
                              AND barcode = @barcode
                              AND @barcode <> '' ) 
            GOTO error100  
                
          BEGIN TRAN INSERTA  
          EXEC [dbo].[XW_GetUpdateTag] 'Color', @UpdateTag OUTPUT
          INSERT  INTO [color] ( [name], barcode, [remark], updateTag )
          VALUES  ( @name, @barcode, @remark, @UpdateTag )   
          IF @@rowcount = 0
            OR @@Error <> 0 
            BEGIN  
              ROLLBACK TRAN INSERTA  
              GOTO error111  
            END   
          COMMIT TRAN INSERTA  
           --if exists(select [barcode]  from [color]  where colorid <>@csid and [name]=@name and barcode<>@barcode and @barcode <> '')   
           --   goto error106   
          GOTO succee  
        END   
       /*修改颜色*/  
      IF @iMode = 'M' 
        BEGIN  
          IF NOT EXISTS(SELECT 1 FROM dbo.[color] WHERE ColorID = @csid) --判断要操作的信息是否存在
            GOTO error107 
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [name] = @name
                              AND @Stats1 = 1 )--不允许名称相同  
            GOTO error100  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [barcode] = @barcode
                              AND @Stats2 = 1 )  --不允许编码相同  
            GOTO error101  
                   
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [name] = @name
                              AND barcode = @barcode
                              AND @barcode <> '' ) 
            GOTO error100  
          SELECT  colorgroupID
          INTO    #tmptable
          FROM    colorgroup
          WHERE   colorgroupID IN ( SELECT  colorgroupid
                                    FROM    colorgrouprelation
                                    WHERE   colorid = @csid )
                  AND colorgroupid IN ( SELECT  colorgroupid
                                        FROM    colorgrouprelation
                                        WHERE   colorid IN ( SELECT colorid
                                                             FROM   color
                                                             WHERE  ( [name] = @name
                                                                      OR ( barcode = @barcode
                                                                           AND @barcode <> ''
                                                                         )
                                                                    )
                                                                    AND colorid <> @csid ) )  
          IF EXISTS ( SELECT  *
                      FROM    #tmptable ) 
            BEGIN  
              DROP TABLE #tmptable         
              GOTO error103  
            END  
          DROP TABLE #tmptable      
     
          BEGIN TRAN   
          SELECT  @oldbar = barcode
          FROM    [color]
          WHERE   colorid = @csid  
          EXEC [dbo].[XW_GetUpdateTag] 'Color', @UpdateTag OUTPUT
          UPDATE  [color]
          SET     [name] = @name, barcode = @barcode, [remark] = @remark, updateTag = @UpdateTag
          WHERE   colorid = @csid  
          IF @@rowcount = 0 
            BEGIN  
              ROLLBACK TRAN   
              GOTO error111  
            END  
          IF @oldbar + '1' <> @barcode + '1' --加一个常量字符串，区分是否有尾部空格  
            BEGIN  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + @barcode + ( SELECT BarCode FROM [Size] c WHERE c.SizeId = a.SizeId )
                                           WHEN cspz = 1 THEN b.barcode + @barcode
                                           WHEN cspz = 2 THEN b.barcode + ( SELECT MAX (BarCode) FROM [Size] c WHERE c.SizeId = a.SizeId )
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   colorid = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '1'  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + ( SELECT BarCode FROM [Size] c WHERE c.SizeId = a.SizeId ) + @barcode
                                           WHEN cspz = 1 THEN b.barcode + @barcode
                                           WHEN cspz = 2 THEN b.barcode + ( SELECT MAX (BarCode) FROM [Size] c WHERE c.SizeId = a.SizeId )
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   colorid = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '2'  
            END   
          COMMIT TRAN  
      		    --系统条码修改后，如果存在唯一码，要删除 ptypeuniquecode
          IF @oldbar <> @barcode 
            BEGIN
              DELETE  FROM ptypeuniquecode
              WHERE   ColorID = @csid 
              DELETE  FROM PtypeUniqueCheck
              WHERE   ColorID = @csid 
            END
          GOTO succee  
        END  
      IF @iMode = 'D' 
        BEGIN  
          IF @csid = '1' 
            GOTO succee  
           
           if exists(select * from BakDly where ColorId =@csid) or
              exists(select * from DlyData where ColorId =@csid) or
              exists(select * from IniGoodsDetail where ColorId =@csid) or
              exists(select * from Goodsstockdetail where ColorId =@csid) or
              exists(select * from BakDlyOrder where ColorId =@csid) 
           GOTO error100  
          --不判断此处了，可以直接删除
          --IF EXISTS ( SELECT  *
          --            FROM    ptypecolor
          --            WHERE   colorid = @csid ) 
          --  GOTO error100  

          --IF EXISTS ( SELECT  *
          --            FROM    ColorGroupRelation
          --            WHERE   colorid = @csid ) 
          --  GOTO error100  
          --  ELSE 
          IF EXISTS(SELECT 1 FROM dbo.AutoPhGrdData WHERE PCTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF EXISTS(SELECT 1 FROM dbo.AutoPhOrderGrdData WHERE PCTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF NOT EXISTS(SELECT 1 FROM dbo.[color] WHERE ColorID = @csid) --判断要删除的信息是否不存在
            GOTO error107 
            
          ELSE 
            BEGIN  
              BEGIN TRAN D  
              DELETE  FROM [color]
              WHERE   colorid = @csid  
              IF @@error <> 0 
                BEGIN  
                  ROLLBACK TRAN D  
                  GOTO error111  
                END  
            delete from ColorGroupRelation where ColorId =@csid 
			delete from ColorGroup where not exists(select * from ColorGroupRelation where ColorId=@csid and ColorGroupID=ColorGroup.ColorGroupID)
			--商品颜色处替换,没有颜色了，替换成均色
          	update PType set ColorIdList='1',ColorGroupid=1,CSPZ =case when SizeGroupid=1 then 3 else 2 end
			where REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',',') in (',',',,') and 
			exists(select * from PtypeColor  where ColorId=@csid and PtypeId=ptype.TypeID)


			update PType set ColorIdList=
				case when left(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),1)=',' 
				then 
					case when RIGHT(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),1)=',' 
						then SUBSTRING(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),2,len(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','))-2)
					else
						RIGHT(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),len(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','))-1)			
					end
				else
					case when RIGHT(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),1)=',' 
						then SUBSTRING(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),0,len(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',',')))
					else 
						REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',',')
					end
				end
			where REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',',') not in (',',',,') and 
			exists(select * from PtypeColor  where ColorId=@csid and PtypeId=ptype.TypeID)         
			delete from ptypecolor where ColorId =@csid
			delete from PtypeBar where ColorId =@csid  
			
              
              IF @@error <> 0 
                BEGIN  
                  ROLLBACK TRAN D  
                  GOTO error111  
                END  
              COMMIT TRAN D  
              GOTO succee  
            END  
        END  
    END  
  IF @tablename = 'S' 
    BEGIN  
      IF @iMode = 'A' 
        BEGIN    
          IF EXISTS ( SELECT  [name]
                      FROM    [size]
                      WHERE   [name] = @name
                              AND @Stats1 = 1 ) 
            GOTO error100 --不允许名称相同  
          IF EXISTS ( SELECT  [name]
                      FROM    [size]
                      WHERE   [barcode] = @barcode
                              AND @Stats2 = 1 ) 
            GOTO error101--不允许编码相同  
          IF EXISTS ( SELECT  *
                      FROM    [size]
                      WHERE   [name] = @name
                              AND barcode = @barcode
                              AND @barcode <> '' ) 
            GOTO error100  
        
          BEGIN TRAN INSERTA  
          EXEC [dbo].[XW_GetUpdateTag] 'Size', @UpdateTag OUTPUT
          INSERT  INTO [size] ( [name], barcode, remark, updateTag )
          VALUES  ( @name, @barcode, @remark, @UpdateTag )   
          IF @@rowcount = 0 
            BEGIN  
              ROLLBACK TRAN INSERTA  
              GOTO error111  
            END   
          COMMIT TRAN INSERTA  
                     --if exists(Select * from [size] where [name]=@name and barcode <> @barcode and @barcode <> '')    
                      --  goto error106  
          GOTO succee  
        END  
    
      IF @iMode = 'M' 
        BEGIN  
          IF NOT EXISTS(SELECT 1 FROM dbo.[SIZE] WHERE SizeID = @csid) --判断要操作的信息是否存在
            GOTO error107 
          IF EXISTS ( SELECT  1
                      FROM    [size]
                      WHERE   sizeid <> @csid
                              AND [name] = @name
                              AND @Stats1 = 1 )--不允许名称相同  
            GOTO error100  
          IF EXISTS ( SELECT  1
                      FROM    [size]
                      WHERE   sizeid <> @csid
                              AND [barcode] = @barcode
                              AND @Stats2 = 1 )  --不允许编码相同  
            GOTO error101  
          IF EXISTS ( SELECT  *
                      FROM    [size]
                      WHERE   [name] = @name
                              AND BarCode = @barcode
                              AND sizeid <> @csid
                              AND @barcode <> '' ) 
            GOTO error100  
      
          SELECT  sizegroupID
          INTO    #tmptables
          FROM    sizegroup
          WHERE   sizegroupID IN ( SELECT sizegroupID
                                   FROM   Sizegrouprelation
                                   WHERE  sizeid = @csid )
                  AND sizegroupID IN ( SELECT sizegroupID
                                       FROM   Sizegrouprelation
                                       WHERE  sizeid IN ( SELECT  sizeid
                                                          FROM    size
                                                          WHERE   ( [name] = @name
                                                                    OR ( barcode = @barcode
                                                                         AND @barcode <> ''
                                                                       )
                                                                  )
                                                                  AND sizeid <> @csid ) )  
          IF EXISTS ( SELECT  *
                      FROM    #tmptables ) 
            BEGIN  
              DROP TABLE #tmptables         
              GOTO error103  
            END  
          DROP TABLE #tmptables         
          BEGIN TRAN   
          SELECT  @oldbar = barcode
          FROM    [size]
          WHERE   sizeid = @csid  
          EXEC [dbo].[XW_GetUpdateTag] 'Size', @UpdateTag OUTPUT
          UPDATE  [size]
          SET     [name] = @name, barcode = @barcode, [remark] = @remark, updateTag = @UpdateTag
          WHERE   sizeid = @csid  
          IF @@rowcount = 0 
            BEGIN  
              ROLLBACK TRAN   
              GOTO error111  
            END  
          IF EXISTS ( SELECT  *
                      FROM    sizegrouprelation sg ,
                              size s
                      WHERE   s.sizeid = sg.sizeid
                              AND sg.sizeid = @csid
                              AND ( s.name = @name )
                              AND sizegroupid IN ( SELECT sg.sizegroupid
                                                   FROM   sizegrouprelation sg ,
                                                          size s
                                                   WHERE  s.sizeid = sg.sizeid
                                                          AND s.Name = @name
                                                          AND sg.sizeid <> @csid ) ) 
            BEGIN  
              ROLLBACK TRAN   
              GOTO error103   
            END  
   
    
          IF @oldbar <> @barcode 
            BEGIN  
--如果条码变动,则更新条码信息  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid ) + @barcode
                                           WHEN cspz = 1 THEN b.barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid )
                                           WHEN cspz = 2 THEN b.barcode + @barcode
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   SizeID = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '1'  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + @barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid )
                                           WHEN cspz = 1 THEN b.barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid )
                                           WHEN cspz = 2 THEN b.barcode + @barcode
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   SizeID = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '2'  
            END  
          COMMIT TRAN  
                    
      		    --系统条码修改后，如果存在唯一码，要删除 ptypeuniquecode
          IF @oldbar <> @barcode 
            BEGIN
              DELETE  FROM ptypeuniquecode
              WHERE   SizeID = @csid 
              DELETE  FROM PtypeUniqueCheck
              WHERE   SizeID = @csid 
            END
          GOTO succee  
        END   
     
    
      IF @iMode = 'D' 
        BEGIN  
          IF @csid = '1' 
            GOTO succee  
          IF EXISTS ( SELECT  *
                      FROM    ptypesize
                      WHERE   sizeid = @csid ) 
            GOTO error100  
          IF EXISTS ( SELECT  *
                      FROM    SizeGroupRelation
                      WHERE   sizeid = @csid ) 
            GOTO error100  
          ELSE IF EXISTS(SELECT 1 FROM dbo.PMdetail WHERE PSTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF EXISTS(SELECT 1 FROM dbo.AutoPhGrdData WHERE PSTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF EXISTS(SELECT 1 FROM dbo.AutoPhOrderGrdData WHERE PSTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF NOT EXISTS(SELECT 1 FROM dbo.[SIZE] WHERE SizeId = @csid) --判断要删除的信息是否不存在
            GOTO error107
          ELSE           
            BEGIN  
                                                          
              BEGIN TRAN D  
              DELETE  FROM [size]
              WHERE   sizeid = @csid  
              IF @@error <> 0 
                BEGIN  
                  ROLLBACK TRAN D  
                  GOTO error111  
                END  
              DELETE  FROM SizeGROUPRELATION
              WHERE   sizeid = @csid  
              IF @@error <> 0 
                BEGIN  
                  ROLLBACK TRAN D  
                  GOTO error111  
                END  
              COMMIT TRAN D  
              GOTO succee  
            END  
        END  
    END   
  succee:  
               
  RETURN 0  
  error111:  
  RETURN -1  
  error100:  
  RETURN -2  
  error101:  
  RETURN -3  
  error102:  
  RETURN -4  
  error103:  
  RETURN -5 --在一个商品中存在颜色名称相同的记录  
  error106:  
  RETURN 1
 --相同颜色不同条码  
  error107:  
  RETURN -7 --删除的信息不存在



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/******************************************20130620********************************************/
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

CREATE  PROCEDURE FZGetBaseInfoCommon  
(  @cMode varchar(5),    
   @szid      int,  
   @typeid int =0  
        
)  
as  
	DECLARE @con INT
	SELECT @con=stats FROM dbo.SysCon WHERE [order]=36

IF @CMODE ='C' --颜色表    
begin    
  if @szid = -1     
  begin    
     SELECT right('00000' + cast(colorid as varchar),5) as PCTypeid, [NAME],BARCODE,REMARK,COLORID FROM COLOR ORDER BY [ORDER]    
  end    
   else IF @SZID=0    
  Begin    
     sELECT  right('00000' + cast(colorid as varchar),5) as PCTypeid,[NAME],BARCODE,REMARK,COLORID FROM COLOR  WHERE COLORID<>1 ORDER BY [ORDER]    
    if exists (Select barcode From color where colorid<>1 and BARCODE <> '' Group by barcode having count(*) >1)    
               or exists (Select [Name] From color where colorid<>1  Group by [Name] having count(*) >1)     
   Return 111    
  End    
   ELSE    
    SELECT  right('00000' + cast(a.colorid as varchar),5) as PCTypeid,A.[ORDER],A.NAME,A.REMARK,A.BARCODE,A.COLORID FROM COLOR A,COLORGROUP B,COLORGROUPRELATION C     
      WHERE A.COLORID =C.COLORID AND B.COLORGROUPID =C.COLORGROUPID  AND  B.COLORGROUPID=@SZID ORDER BY A.[ORDER]    
end     
IF @CMODE ='CG' --颜色组表    
   BEGIN    
 if @szid=-1    
        SELECT [NAME],REMARK,COLORGROUPID FROM COLORGROUP WHERE COLORGROUPID=1  and not (LEFT([name],5)='系统颜色组' and remark='系统升级自动生成') ORDER BY [ORDER]    
 else    
             SELECT [NAME],REMARK,COLORGROUPID FROM COLORGROUP WHERE COLORGROUPID<>1 and not (LEFT([name],5)='系统颜色组' and remark='系统升级自动生成')  ORDER BY [ORDER]    
    END     
IF @CMODE ='S'--尺码表    
   BEGIN    
 if @szid = -1    
 begin    
           SELECT right('00000' + cast(sizeid as varchar),5) as PSTypeid,[NAME],BARCODE,REMARK,SIZEID FROM [SIZE] ORDER BY [ORDER],sizeid    
 end    
        else IF @SZID=0    
 Begin    
           SELECT right('00000' + cast(sizeid as varchar),5) as PSTypeid,[NAME],BARCODE,REMARK,SIZEID FROM [SIZE]  WHERE SIZEID<>1 ORDER BY [ORDER],sizeid    
     if exists (Select barcode From [SIZE] where SIZEID<>1 and BARCODE <> '' Group by barcode having count(*) >1)     
              or exists (Select [Name] From [SIZE] where SIZEID<>1  Group by [Name] having count(*) >1)     
  Return 112    
     if exists (Select [Name] From [SIZE] where SIZEID<>1 and BARCODE <> '' Group by [Name] having count(*) >1)     
  Return 113                 
 End    
        ELSE    
          SELECT right('00000' + cast(a.sizeid as varchar),5) as PSTypeid,A.NAME,A.REMARK,A.BARCODE,A.SIZEID FROM [SIZE] A,SIZEGROUP B,SIZEGROUPRELATION C     
          WHERE A.SIZEID =C.SIZEID AND B.SIZEGROUPID =C.SIZEGROUPID  AND  B.SIZEGROUPID =@SZID ORDER BY A.[ORDER],a.sizeid  
   END    
IF @CMODE ='SG' --尺码组表    
   BEGIN    
 if @szid=-1    
        SELECT [NAME],REMARK,SIZEGROUPID FROM SIZEGROUP  ORDER BY [ORDER]    
 else    
              SELECT [NAME],REMARK,SIZEGROUPID FROM SIZEGROUP WHERE SIZEGROUPID<>1 ORDER BY [ORDER]    
 END    
if @cmode = 'AT' 
begin  
  IF @szid = 0   
    select typeid,typename,comment,Choose from assisttype order by typeid  
  else   
   select typeid,typename,comment,Choose from assisttype where typeid = @SZID   
end  
if @cmode = 'AV'  
begin  
  IF @typeid =0  
  BEGIN  
   if @szid = 0   
     select AttributeID,Typeid,TypeName,UserName,UserCode  from AssistAttribute 
     ORDER BY CASE WHEN @con = 0 THEN TypeName 
     ELSE usercode END
   else   
     select AttributeID,Typeid,TypeName,UserName,UserCode  from AssistAttribute where AttributeID = @SZID 
     ORDER BY CASE WHEN @con = 0 THEN TypeName ELSE usercode END
  END  
  ELSE  
  BEGIN  
   if @szid = 0   
     select AttributeID,Typeid,TypeName,UserName,UserCode  from AssistAttribute where typeid=@typeid
      ORDER BY CASE WHEN @con = 0 THEN TypeName ELSE usercode END
 
   else   
     select AttributeID,Typeid,TypeName,UserName,UserCode  from AssistAttribute where typeid=@typeid and AttributeID = @SZID 
     ORDER BY CASE WHEN @con = 0 THEN TypeName ELSE usercode END

  END  
end  
/*  
IF @CMODE ='PS'--季节    
     BEGIN    
         IF @SZID=0    
            SELECT USERCODE,[Name],COMMENT,CODE FROM PTYPE_SEASON    
         ELSE    
            SELECT USERCODE,[Name],COMMENT,CODE FROM PTYPE_SEASON WHERE CODE =@SZID--特别说明此处传季节编码    
     END    
IF @CMODE ='PC'--品牌    
     BEGIN    
         IF @SZID=0    
            SELECT USERCODE,[Name],COMMENT,CODE,pBarCode,VerifyNum     
                 FROM PTYPE_CATEGORY    
         ELSE    
            SELECT USERCODE,[Name],COMMENT,CODE,pBarCode,VerifyNum     
                FROM PTYPE_CATEGORY WHERE CODE =@SZID--特别说明此处传品牌编码    
     END    
IF @CMODE ='PM'--面料    
     BEGIN    
         IF @SZID=0    
            SELECT USERCODE,[NAME] ,COMMENT,CODE FROM PTYPE_MATERIAL    
         ELSE    
            SELECT USERCODE,[NAME] ,COMMENT,CODE FROM PTYPE_MATERIAL WHERE CODE =@SZID--特别说明此处传面料编码    
     END    
IF @CMODE ='PY'--年度    
     BEGIN    
         IF @SZID=0    
            SELECT USERCODE ,[NAME] ,COMMENT,CODE FROM PTYPE_YEAR    
         ELSE    
            SELECT USERCODE,[NAME],COMMENT,CODE FROM PTYPE_YEAR WHERE CODE =@SZID--特别说明此处传年度编码    
     END    
---    
IF @CMODE ='PA5'--年度    
     BEGIN    
         IF @SZID=0    
            SELECT USERCODE ,UserName as [NAME] ,COMMENT,attid as CODE FROM AttributeExt where subno  = (select subno  from sysdata where subName  = 'Pattribute3')     
         ELSE    
            SELECT USERCODE ,UserName as [NAME] ,COMMENT,attid as CODE FROM AttributeExt WHERE attid =@SZID--特别说明此处传年度编码    
     END    
IF @CMODE ='PA6'--年度    
     BEGIN    
         IF @SZID=0    
            SELECT USERCODE ,UserName as [NAME] ,COMMENT,attid as CODE FROM AttributeExt where subno  = (select subno  from sysdata where subName  = 'Pattribute4')     
         ELSE    
            SELECT USERCODE ,UserName as [NAME] ,COMMENT,attid as CODE FROM AttributeExt WHERE attid =@SZID--特别说明此处传年度编码    
     END    
IF @CMODE ='PA7'--年度    
     BEGIN    
         IF @SZID=0    
            SELECT USERCODE ,UserName as [NAME] ,COMMENT,attid as CODE FROM AttributeExt where subno  = (select subno  from sysdata where subName  = 'Pattribute5')     
         ELSE    
            SELECT USERCODE ,UserName as [NAME] ,COMMENT,attid as CODE FROM AttributeExt WHERE attid =@SZID--特别说明此处传年度编码    
     END    
IF @CMODE ='PA8'--年度    
     BEGIN    
         IF @SZID=0    
            SELECT USERCODE ,UserName as [NAME] ,COMMENT,attid as CODE FROM AttributeExt where subno  = (select subno  from sysdata where subName  = 'Pattribute6')     
         ELSE    
            SELECT USERCODE ,UserName as [NAME] ,COMMENT,attid as CODE FROM AttributeExt WHERE attid =@SZID--特别说明此处传年度编码    
     END    
----    
*/  
/*
IF @CMODE='PMB'-- 配码包    
      BEGIN    
          IF @SZID=0    
             SELECT P.[ID] ,P.[NAME],S.[NAME] AS SIZENAME,P.SIZEGROUPID,P.QTY,S.[ORDER] FROM PMMAIN P,SIZEGROUP S WHERE S.SIZEGROUPID = P.SIZEGROUPID ORDER BY S.[ORDER]    
          ELSE    
              SELECT P.[ID] ,P.[NAME],S.[NAME] AS SIZENAME,P.SIZEGROUPID,P.QTY ,S.[ORDER] FROM PMMAIN P,SIZEGROUP S WHERE [ID]=@SZID AND S.SIZEGROUPID = P.SIZEGROUPID ORDER BY S.[ORDER]    
      END    
IF @CMODE='PMBC'    
   BEGIN    
          IF @SZID=0    
               SELECT [ID],SIZEGROUPID,QTY FROM PMMAIN      
          ELSE    
               SELECT [ID],SIZEGROUPID,QTY FROM PMMAIN  WHERE SIZEGROUPID =@SZID    
      END    
IF @CMODE='PMBD'-- 配码包明细    
      BEGIN    
          IF @SZID=0    
              SELECT B.[NAME], A.QTY FROM PMDETAIL A,[SIZE]  B WHERE A.SIZEID =B.SIZEID ORDER BY B.[ORDER]    
          ELSE    
              SELECT B.[NAME],A.QTY  FROM PMDETAIL A,[SIZE]  B, PMMAIN C ,SIZEGROUPRELATION D    
              WHERE  [ID]=@SZID AND ( A.SIZEGROUPID = C.SIZEGROUPID ) AND      
              ( A.PMID =C.ID ) AND      ( B.SIZEID = D.SIZEID ) AND      
              ( A.SIZEID = B.SIZEID )  AND        ( C.SIZEGROUPID = D.SIZEGROUPID )    ORDER BY D.[ORDER]    
      END    
 */
IF @CMODE='ZH'    
BEGIN    
      IF @SZID=0    
       SELECT * FROM DLYSALEPROMNO_ZHMAIN WHERE IFSTOP=0    
      ELSE    
 SELECT * FROM DLYSALEPROMNO_ZHMAIN WHERE IFSTOP=0 AND ORDERID=@SZID    
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].[FzUpdateP]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FzUpdateP]
GO






/****** Object:  Stored Procedure dbo.F_B_UpdateP    Script Date: 2004-09-02 8:40:11 ******/
--  ********************************************************************************************
--  ||                                                                                        
--  ||   过程名称： F_B_UpdateP                                    
--  ||   过程功能：添加基本信息--仓库
--  ||=========================================================================================
--  ||   参数说明：  参数名称         类型            意义                     输入输出
--  ||            -----------------------------------------------------------------------------
--  ||  	@Parid 		varchar(50),                                             --父亲ID号1
--  ||  	@dbname        	varchar(30),                                             --操作的数据库表名2
--  ||  	@FullName 	varchar(66),                                             --商品全名3
--  ||  	@Name		varchar(30),                                             --商品简名4
--  ||  	@UserCode 	varchar(26),                                             --用户编码5
--  ||  	@Standard 	varchar(20),                                             --商品规格6
--  ||  	@Type	 	varchar(20),                                             --商品类型7
--  ||  	@Area	 	varchar(30),                                             --商品产地8
--  ||  	@Unit1 		varchar(8),                                               --商品单位1  9
--  ||  	@Unit2 		varchar(8),                                               --商品单位2  10
--  ||  	@UnitRate1 	numeric(24,10),                                        --单位关系1  11
--  ||  	@UnitRate2 	numeric(24,10),                                        --单位关系2  12
--  ||  	@preprice1 	numeric(24,10),                                        --预设售价1  13
--  ||  	@preprice2 	numeric(24,10),                                        --预设售价2  14
--  ||  	@preprice3 	numeric(24,10),                                        --预设售价3  15
--  ||  	@preprice4 	numeric(24,10),                                        --预设售价4  16
--  ||	@retailprice        numeric(24,10),                                         零售价
--  ||        @minprice          numeric(24,10),			             最低售价
--  ||  	@LifeMonth 	smallint,                                                    --保质期月17
--  ||  	@LifeDay 	smallint,                                                    --保质期天18
--  ||  	@CostMode	smallint,                                                    --成本算法19
--  ||  	@Comment 	varchar(256),                                           --备注20
--  ||  	@namepy	varchar(60),                                             --全名简拼21
--  ||  	@Barcode	varchar(30),                                             --商品条码22
--  ||  	@sizegroupid      int,                                                           --尺码组23
--  ||  	@colorgroupid    int,                                                           --颜色组24
--  ||  	@breakwarn       numeric(24,10),                                       --断码报警数25
--  ||  	@Formatid           varchar(10),                                             --条码格式26
--  ||  	@cspz                int,                                                            --颜色尺码配置
--  ||  	@backRec        int  output,--
--  ||  	@material	int,                                                            --面料
--  ||  	@season           int,                                                           --季节
--  ||  	@category         int,                                                           --品牌
--  ||  	@year               int,                                                            --年度
--  ||               -- @SPPIC              image,                                                      -- 商品图片
--  ||  	@trade                bit,                                                            --可否换货0：不能换货，1：可以换货
--  ||  	@stop                 bit                                                             -- 是否停用
--  ||        @discount          int					折扣0
--  ||        @discount1        int                                                              折扣1
--  ||        @discount2	int					折扣2
--  ||        @discount3	int					折扣3
--  ||=========================================================================================   
--  ||    返回值： 值               说明               
--  ||                   -1                  -- 数据库操作失败！
--  ||                   -2                -- 此记录已经过账，不能再分类！
--  ||                   -3                  -- 父亲ID号不存在！
--  ||                   -4              名称不能相同
--  ||	-5		  编码不能相同
--  ||	－7		  名称和编码不能同时相同	
--  ||                   -6                 有相同条码的记录存在
--  ||=========================================================================================

/*
cqhua 2011-8-29
尺码组改变
*/

CREATE PROCEDURE FzUpdateP
    (
      @typeId VARCHAR(50),--商品编码
      @dbname VARCHAR(30),--所操作的数据表名
      @FullName VARCHAR(66),--商品全名
      @Name VARCHAR(30),--商品简名
      @UserCode VARCHAR(26),--用户编码
      @Standard VARCHAR(20),--商品规格
      @Type VARCHAR(20),--商品类型
      @Area VARCHAR(30),--商品产地
      @Unit1 VARCHAR(8),--商品单位1
      @Unit2 VARCHAR(8),--商品单位2
      @UnitRate1 NUMERIC(24, 10),--单位关系1
      @UnitRate2 NUMERIC(24, 10),--单位关系2
      @preprice1 NUMERIC(24, 10),--预设售价1
      @preprice2 NUMERIC(24, 10),--预设售价2
      @preprice3 NUMERIC(24, 10),--预设售价3
      @preprice4 NUMERIC(24, 10),--预设售价4
      @retailprice NUMERIC(24, 10),--零售价
      @minprice NUMERIC(24, 10),--最低售价
      @LifeMonth SMALLINT,--保质期月
      @LifeDay SMALLINT,--保质期日
      @CostMode SMALLINT,--成本算法
      @Comment VARCHAR(250),--备注
      @namepy VARCHAR(60),--商品全名简拼
      @Barcode VARCHAR(30),--商品条码
      @sizegroupid INT,--尺码组Id 
      @colorgroupid INT,--颜色组Id
      @breakwarn NUMERIC(24, 10),  -- 断码报警数
      @cspz INT,       --
      @material VARCHAR(30),--面料
      @season INT, --季节
      @category INT, --品牌
      @year INT,  --年度
      @FORMATID VARCHAR(10),                                            --条码格式
         --    @SPPIC              image,                                                      -- 商品图片
      @trade INT,                                                            --可否换货0：不能换货，1：可以换货
      @stop BIT,  --是否停用
      @discount NUMERIC(24, 10),
      @discount1 NUMERIC(24, 10),
      @discount2 NUMERIC(24, 10),
      @discount3 NUMERIC(24, 10),
      @changechild INT,
      @StopDate VARCHAR(10) = '',	-- 是否修改儿子的成本算法 0 不修改, 1 修改
      @ColorIdList VARCHAR(1000) = '',
      @SizeIdList VARCHAR(1000) = '',
      @iPa1 INT,
      @iPa2 INT,
      @iPa3 INT,
      @iPa4 INT,
      @IssueDate VARCHAR(10) = '',
      @Custom1 VARCHAR(255),
      @Custom2 VARCHAR(255),
      @Custom3 VARCHAR(255),
      @Custom4 VARCHAR(255),
      @Custom5 VARCHAR(255),
      @btypeid VARCHAR(50) = '',
      @changerule INT,
	  @singleunit INT = 0,
      @BuyUnit INT = 1,
      @SaleUnit INT = 1,
      @PhUnit INT =1,
      @GoodsUnit INT = 1,
      @AttributeId1 INT = 0,                      --与辅助属性类型对应
	  @AttributeId2 INT = 0,
      @AttributeId3 INT = 0,
	  @AttributeId4 INT = 0,
	  @AttributeId5 INT = 0,
	  @AttributeId6 INT = 0,
	  @AttributeId7 INT = 0,
	  @AttributeId8 INT = 0,
	  @IsDeleteUniq INT = 0
    )
AS 
    SET nocount ON
    DECLARE @OldCostMode INT
    DECLARE @szptypeid VARCHAR(50)
    DECLARE @szKtypeid VARCHAR(50)
    DECLARE @Qty NUMERIC(24, 10)
    DECLARE @Total NUMERIC(24, 10)
    DECLARE @lsonnum INT
    DECLARE @ROOT_ID VARCHAR(50)
    DECLARE @oldBar VARCHAR(30)        
    DECLARE @oldBcon VARCHAR(30)
    DECLARE @oldStop BIT
    DECLARE @BarConID INT      
    DECLARE @oldCGid INT,
        @oldSGid INT     
    DECLARE @cid INT,
        @cbar VARCHAR(10),
        @sid INT,
        @sbar VARCHAR(10),
        @bar VARCHAR(50)   
    DECLARE @UpdateTag INT
	DECLARE @ColorIdListOld varchar(2000)	
	declare @re int	
	DECLARE @SizeNameList varchar(2000) 
	EXEC @re =CheckGroupCanChange  @typeId,@SizeIdList,@SizeNameList OutPut
	IF @re<>0 GOTO error154
    SELECT  @OldCostMode = [costmode],
            @oldBar = barcode,
            @oldBcon = formatid,
			@ColorIdListOld=ColorIdList,
			@oldStop = [Stop]
    FROM    ptype
    WHERE   typeId = @typeId
	
    IF @oldBar <> @BarCode
        OR @oldBcon <> @FORMATID
        OR @IsDeleteUniq = 1  --系统条码修改后，如果存在唯一码，要删除 ptypeuniquecode
        BEGIN
            DELETE  FROM ptypeuniquecode
            WHERE   ptypeid = @Typeid
            DELETE  FROM PtypeUniqueCheck
            WHERE   ptypeid = @Typeid	
        END
	
    SELECT  @ROOT_ID = '00000'
    DECLARE @Stats1 INT
    DECLARE @Stats2 INT
    SELECT  @Stats1 = stats
    FROM    syscon
    WHERE   [order] = 81
    SELECT  @Stats2 = stats
    FROM    syscon
    WHERE   [order] = 82
    IF @Stats1 = 1 
        IF EXISTS ( SELECT  [typeid]
                    FROM    ptype
                    WHERE   typeId <> @typeId
                            AND ( fullname = @fullname
                                  AND [deleted] <> 1
                                ) ) 
            GOTO error114
--名称不能相同
    IF @Stats2 = 1 
        IF EXISTS ( SELECT  [typeid]
                    FROM    ptype
                    WHERE   typeId <> @typeId
                            AND ( usercode = @usercode
                                  AND [deleted] <> 1
                                ) ) 
            GOTO error115
--编码不能相同
    IF @Stats1 = 0
        AND @Stats2 = 0 
        IF EXISTS ( SELECT  [typeid]
                    FROM    ptype
                    WHERE   typeId <> @typeId
                            AND ( fullname = @fullname
                                  AND usercode = @usercode
                                  AND [deleted] <> 1
                                ) ) 
            GOTO error117
    IF EXISTS ( SELECT  getid
                FROM    dbo.GetIdListTable(@ColorIdList)
                WHERE   getid NOT IN ( SELECT   colorid
                                       FROM     color ) ) 
        GOTO error1117
    IF EXISTS ( SELECT  getid
                FROM    dbo.GetIdListTable(@SizeIdList)
                WHERE   getid NOT IN ( SELECT   sizeid
                                       FROM     size ) ) 
        GOTO error1118

    IF @Issuedate = '' 
        SET @Issuedate = CONVERT(CHAR(10), GETDATE(), 121)
      
    IF ( LEN(RTRIM(LTRIM(@Barcode))) > 0 ) 
        BEGIN  
            IF EXISTS ( SELECT  [typeid]
                        FROM    ptype
                        WHERE   [typeId] <> @typeId
                                AND ( Barcode = @Barcode )
                                AND [deleted] <> 1 ) 
                GOTO error200
        END
    GOTO UpdateOne
    UpdateOne:
--	如果 sonnum>0 则修改儿子成本算法，并且合并库存
--只有加权了。所以不需要了
-- 	if (@lsonnum > 0) and (@changechild = 1)
-- 	begin
-- 		select @szptypeid = @typeid + '%'
-- 		exec @stats1 = changecostmode 1, @szptypeid, @costmode -- 修改成本算法，合并期初批次
-- 		if @stats1 < 0 goto error1		
-- 		exec @stats1 = changecostmode 2, @szptypeid, @costmode -- 修改成本算法，合并当前批次
-- 		if @stats1 < 0 goto error1		
-- 	end

	IF @SizeIdList ='1'
		SET @sizegroupid =1
    EXEC [dbo].[XW_GetUpdateTag] 'Ptype', @UpdateTag OUTPUT
    UPDATE  [dbo].[ptype]
    SET     [UserCode] = @UserCode,
            [FullName] = @FullName,
            [Name] = @Name,
            [Standard] = @Standard,
            [Type] = @Type,
            [Area] = @Area,
            [Unit1] = @Unit1,
            [Unit2] = @Unit2,
            [UnitRate1] = @UnitRate1,
            [UnitRate2] = @UnitRate2,
            --retailprice = @retailprice,
            [costmode] = @CostMode,
            [Comment] = @Comment,
            [namepy] = @namepy,
            [Barcode] = @Barcode,
            breakwarn = @breakwarn,
            formatid = @FORMATID,
            cspz = @cspz,
            trade = @trade,
            stop = @stop,
            StopDate = @StopDate,
            issueDate = @issueDate,
            ColorIdList = @ColorIdList,
            SizeIdList = @SizeIdList,
            updateTag = @UpdateTag,
            PCustom1 = @Custom1,
            PCustom2 = @Custom2,
            PCustom3 = @Custom3,
            PCustom4 = @Custom4,
            PCustom5 = @Custom5,
            btypeid1 = @btypeid,
            changerule = @changerule,
			sizegroupid=@sizegroupid,
			singleunit = @singleunit,
            BuyUnit = @BuyUnit,
            SaleUnit = @SaleUnit,
            PhUnit = @PhUnit,
            GoodsUnit = @GoodsUnit,
            mininumprice = @minprice
    WHERE   [typeId] = @typeId
    IF @@error < 0 
        GOTO error1
    DELETE  ptypeColor
    WHERE   ptypeid = @typeId
          
    IF @@error <> 0 --写数据失败回滚事务
        BEGIN
            GOTO error1
        END  
    INSERT  INTO PtypeColor ( Ptypeid, Colorid )
            SELECT  @typeId,
                    getid
            FROM    dbo.GetIdListTable(@ColorIdList)
    IF @@error <> 0 --写数据失败回滚事务
        BEGIN
            GOTO error1
        END  

    DELETE  ptypeSize
    WHERE   ptypeid = @typeId
          
    IF @@error <> 0 --写数据失败回滚事务
        BEGIN
            GOTO error1
        END  
    INSERT  INTO ptypeSize ( Ptypeid, Sizeid )
            SELECT  @typeId,
                    getid
            FROM    dbo.GetIdListTable(@SizeIdList)
    IF @@error <> 0 --写数据失败回滚事务
        BEGIN
            GOTO error1
        END   
    IF @stop = 0 
        BEGIN
            UPDATE  ptype
            SET     stop = 0,
                    updateTag = @UpdateTag
            WHERE   typeid = LEFT(@typeId, LEN(typeid))  --下级启用，上级也启用
        END
    IF @stop = 1 
        BEGIN
            IF EXISTS ( SELECT  *
                        FROM    ptype
                        WHERE   sonnum > 0
                                AND typeid = @typeid ) 
                UPDATE  ptype
                SET     stop = 1,
                        updateTag = @UpdateTag
                WHERE   LEFT(typeid, LEN(@typeid)) = @typeid
        END
    
	--IF @oldStop <> @stop
	--update dbo.Ptype set [stop] =@Stop where LEFT(typeid, LEN(@typeid)) = @typeid   
			
	--商品颜色不包含在已有的颜色组中，新增颜色组
	--IF @ColorIdListOld<>@ColorIdList and not EXISTS(SELECT * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZCS') 
	--BEGIN
	--	IF OBJECT_ID('tempdb..#TT') IS NOT NULL
	--		DROP TABLE #TT
	--	SELECT * INTO #TT FROM dbo.fn_split(@colorIdlist,',')
		
	--	IF NOT EXISTS (SELECT 1 FROM colorGroupRelation c INNER JOIN #TT t ON c.colorid=t.a GROUP BY c.ColorGroupId HAVING(COUNT(1)=(SELECT COUNT(1) FROM #TT)))
	--	BEGIN
	--		INSERT INTO colorGroup(name,remark,sysrow,[order])  select (select '系统颜色组'+(select Convert(varchar(10),isnull(max(colorGroupid),1)) from colorGroup)) as name,'系统升级自动生成',0,10000
	--		INSERT INTO colorGroupRelation(colorGroupID,colorid,rec,[order]) select @@identity,getid,0,iorder from  GetIdListTable(@colorIdlist)
	--	END
	--	UPDATE Ptype SET ColorGroupID = 1 WHERE   typeid=@Typeid AND ColorGroupID=0 AND @colorIdlist ='1'
		
	--	UPDATE Ptype SET ColorGroupID = S.Colorgroupid
	--	FROM (
	--		SELECT TOP 1 ColorGroupId
	--		FROM colorGroupRelation 
	--		WHERE ColorGroupId IN(
	--		SELECT c.ColorGroupId FROM colorGroupRelation c INNER JOIN #TT t ON c.colorid=t.a 
	--		GROUP BY c.ColorGroupId HAVING(COUNT(1)=(SELECT COUNT(1) FROM #TT))
	--		)
	--		GROUP BY ColorGroupId
	--		ORDER BY COUNT(1)
	--	) S
	--	WHERE typeid=@Typeid
	--	select @@ROWCOUNT
	--END



    IF ( LEN(RTRIM(LTRIM(@Barcode))) = 0 ) 
        DELETE  ptypebar
        WHERE   ptypeid = @Typeid
    ELSE 
        BEGIN  
            IF EXISTS ( SELECT  ptypeid
                        FROM    PtypeBar
                        WHERE   Ptypeid = @Typeid ) 
                UPDATE  ptypebar
                SET     FullBarCode = REPLACE(FullBarCode, @oldBar, @Barcode)
                WHERE   Ptypeid = @Typeid
            ELSE 
                GOTO updateb
        END
    IF @@error <> 0 
        GOTO error1

    IF ( LEN(RTRIM(LTRIM(@Barcode))) > 0 ) 
        GOTO updateb  
    GOTO succee
     
    updateb:

    BEGIN
        DELETE  ptypebar
        WHERE   Ptypeid = @typeid   --改成全删除0026093: 商品条码和颜色尺码的条码都是1位，商品条码一改变，系统码的最后一位也跟着变了 
      --and (not exists(select 1 from (select @typeid as typeid,getid as colorid from dbo.GetIDListTable(@ColorIdList) ) ls  
      --                where ls.typeid = ptypebar.ptypeid and ls.colorid = ptypebar.colorid) 
      --     or not exists(select 1 from (select @typeid as typeid,getid as sizeid from dbo.GetIDListTable(@sizeIdList) ) ls1  
     --                 where ls1.typeid = ptypebar.ptypeid and ls1.sizeid = ptypebar.sizeid) 
     --or @oldBcon <> @FORMATID)
          
--    if @oldBar <> @BarCode     
        IF ( SELECT MAX(Sonnum)
             FROM   Ptype
             WHERE  typeid = @typeid
           ) = 0 
            BEGIN
            EXEC GeneratePtypeBar @Formatid,@typeId,@cspz,@Barcode,@ColorIdList,@SizeIdList,@AttributeId1,@AttributeId2,@AttributeId3,@AttributeId4,@AttributeId5,@AttributeId6,@AttributeId7,@AttributeId8,@Btypeid    
            END
    END     

     
    IF @FORMATID = 'bsc' 
        SELECT  @BarConID = 1
    ELSE 
        IF @FORMATID = 'bcs' 
            SELECT  @BarConID = 0
        ELSE 
            SELECT  @BarConID = 2
    UPDATE  sysdata
    SET     subvalue = @BarConID
    WHERE   subno = 25

    succee:   
    RETURN 0
    error1:
    RETURN -1
    error2:
    RETURN -2
    error114:
    RETURN -4
    error115:
    RETURN -5 
    error117:
    RETURN -7
    error200:
    RETURN -6
    error1117:
    RETURN -17
--颜色不存存在
    error1118:
    RETURN -18
	
	error154:
    RETURN -154
--尺码不存存在





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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








CREATE        PROCEDURE FNimport_FzInsertP1
(	
	@parid   varchar(50),
	@FullName 	varchar(66),                                             --父类ID
	@Name		varchar(30),                                             --商品简名4
	@UserCode 	varchar(26),                                             --用户编码5
	@Unit1 		varchar(8),                                               --商品单位1  9
	@Barcode	varchar(30),                                             --商品条码22
	@StopDate       varchar(10) ='',					 -- 停用日期
    @Issuedate 	varchar(10)='',						 -- 上市日期
	@colorname      varchar(1000),						 -- 颜色名称
	@sizename       varchar(1000),						 -- 尺码名称
    @category       varchar(100),                                             --品牌
	@season         varchar(100),                                             --季节
    @fz1       varchar(100),                                             --辅助属性1
    @fz2       varchar(100),                                             --辅助属性2
    @fz3       varchar(100),                                             --辅助属性3
    @fz4       varchar(100),                                             --辅助属性4
    @fz5       varchar(100),                                             --辅助属性5
    @fz6       varchar(100),                                             --辅助属性6
	@retailprice    varchar(20),		            			--零售价
	@preprice1 	varchar(20),                                         --预设售价1  13
	@preprice2 	varchar(20),                                         --预设售价2  14
	@preprice3 	varchar(20),                                         --预设售价3  15
	@preprice4 	varchar(20),                                         --预设售价4  16
	@discount1      varchar(20),
	@discount2      varchar(20),
	@discount3	varchar(20),
	@discount4	varchar(20),
	@prebuyprice1  varchar(20),
	@prebuyprice2  varchar(20),
	@prebuydis1  varchar(20),
	@prebuydis2  varchar(20),
	@outid          varchar(100) output,
	@outstr          varchar(200) output

) 
as 
SET NOCOUNT ON
DECLARE @newtypeid varchar(50)
SET @newtypeid=''
DECLARE @backRec int 
DECLARE @ColorID varchar(10)
DECLARE @SizeID varchar(10)
DECLARE @Qty int
DECLARE @Qty1 int
SET @ColorID =0
SET @SizeID =0 
SET @Qty =0 
SET @Qty1 =0 
DECLARE @returnPym varchar(100)
DECLARE @errstr varchar(200)
SET @errstr =''
DECLARE @RE int
SET @RE =0

declare @ColorIdList varchar(1000)
declare @sizeIdList varchar(1000)

IF LTRIM(RTRIM(@FullName))=''
BEGIN
	SET @outstr='商品全名不能为空'
	RETURN -27
END

EXEC @re=FNimport_CheckChar @UserCode,@outstr output
IF @re<0
BEGIN
	return @re
END

EXEC @re=FNimport_CheckChar @FullName,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @Name,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @Unit1,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @Barcode,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @StopDate,@outstr output
IF @re<0
BEGIN
	return @re
END

EXEC @re=FNimport_CheckChar @Issuedate,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @colorname,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @sizename,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @category,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @season,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @fz1,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @fz2,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @fz3,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @fz4,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @fz5,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @fz6,@outstr output
IF @re<0
BEGIN
	return @re
END

/*
SET @parid=''
SELECT @parid =typeid from Ptype where fullname =@parFullname
IF @parid=''
BEGIN
	SET @errstr ='父类商品'+@parFullname+'不存在'
	RAISERROR(@errstr,16,1)
END
*/

IF LEN(@parid)=50
BEGIN
	SET @re =-10
	SET @outstr='超出系统允许的最大层数10'
	return @re
END

DECLARE	@Tretailprice   numeric(24,10)		            		--零售价
DECLARE	@Tpreprice1 	numeric(24,10)                                         --预设售价1  13
DECLARE	@Tpreprice2 	numeric(24,10)                                         --预设售价2  14
DECLARE	@Tpreprice3 	numeric(24,10)                                         --预设售价3  15
DECLARE	@Tpreprice4 	numeric(24,10)                                         --预设售价4  16
DECLARE	@Tdiscount1     numeric(24,10)
DECLARE @Tdiscount2      numeric(24,10)
DECLARE @Tdiscount3	numeric(24,10)
DECLARE @Tdiscount4	numeric(24,10)

DECLARE @Tbuyprice1	numeric(24,10)
DECLARE @Tbuyprice2	numeric(24,10)

DECLARE @Tbuydis1	numeric(24,10)
DECLARE @Tbuydis2	numeric(24,10)



IF ISNUMERIC(@retailprice)=0 
	SET @Tretailprice =0
ELSE
BEGIN
	SET @Tretailprice=Convert(numeric(24,2),@retailprice)
END
IF ISNUMERIC(@preprice1)=0 
	SET @Tpreprice1 =0
ELSE
    	SET @Tpreprice1=Convert(numeric(24,2),@preprice1)
IF ISNUMERIC(@preprice2)=0 
	SET @Tpreprice2 =0
ELSE
    	SET @Tpreprice2=Convert(numeric(24,2),@preprice2)
IF ISNUMERIC(@preprice3)=0 
	SET @Tpreprice3 =0
ELSE
    	SET @Tpreprice3=Convert(numeric(24,2),@preprice3)
IF ISNUMERIC(@preprice4)=0  
	SET @Tpreprice4 =0
ELSE
    	SET @Tpreprice4=Convert(numeric(24,2),@preprice4)

IF ISNUMERIC(@discount1)=0  
	SET @Tdiscount1 =0
ELSE
    	SET @Tdiscount1=Convert(numeric(24,2),@discount1)
IF ISNUMERIC(@discount2)=0  
	SET @Tdiscount2 =0
ELSE
    	SET @Tdiscount2=Convert(numeric(24,2),@discount2)
IF ISNUMERIC(@discount3)=0
	SET @Tdiscount3 =0
ELSE
    	SET @Tdiscount3=Convert(numeric(24,2),@discount3)
IF ISNUMERIC(@discount4)=0 
	SET @Tdiscount4 =0
ELSE
    	SET @Tdiscount4=Convert(numeric(24,2),@discount4)

IF ISNUMERIC(@prebuyprice1)=0 
	SET @Tbuyprice1 =0
ELSE
   	SET @Tbuyprice1=Convert(numeric(24,2),@prebuyprice1)

IF ISNUMERIC(@prebuyprice2)=0  
	SET @Tbuyprice2 =0
ELSE
   	SET @Tbuyprice2=Convert(numeric(24,2),@prebuyprice2)

IF ISNUMERIC(@prebuydis1)=0  
	SET @Tbuydis1 =0
ELSE
   	SET @Tbuydis1=Convert(numeric(24,2),@prebuydis1)

IF ISNUMERIC(@prebuydis2)=0 
	SET @Tbuydis2 =0
ELSE
   	SET @Tbuydis2=Convert(numeric(24,2),@prebuydis2)


IF @Tretailprice<0
	SET @Tretailprice =0

IF @Tpreprice1<0
	SET @Tpreprice1 =0

IF @Tpreprice2<0
	SET @Tpreprice2 =0
IF @Tpreprice3<0
	SET @Tpreprice3 =0
IF @Tpreprice4<0
	SET @Tpreprice4 =0

IF @Tdiscount1<0 OR @Tdiscount1>100
	SET @Tdiscount1 =0

IF @Tdiscount2<0 OR @Tdiscount2>100
	SET @Tdiscount2 =0
IF @Tdiscount3<0 OR @Tdiscount3>100
	SET @Tdiscount3 =0

IF @Tdiscount4<0 OR @Tdiscount4>100
	SET @Tdiscount4 =0

IF @Tbuyprice1<0
	SET @Tbuyprice1 =0


IF @Tbuyprice2<0
	SET @Tbuyprice2 =0
IF @Tbuydis1<0 OR @Tbuydis1>100
	SET @Tbuydis1 =0
IF @Tbuydis2<0 OR @Tbuydis2>100
	SET @Tbuydis2 =0





DECLARE @cspz int 
SET @cspz =-1 -- 3 颜色尺码都不需要

DECLARE @AssistTypeid varchar(10)
DECLARE @Attributeid varchar(10)
--SET @parid =@parFullname
EXEC @returnPym = FN_getPy @FullName
IF @UserCode=''
	SET @UserCode='New Add-'+@returnPym

DECLARE @formatid varchar(100)
SET @formatid='1'
IF @parid=''
	SET @parid='00000'

SELECT @formatid =formatid FROM Ptype where typeid= @parid
IF @formatid='' or  @formatid='1'
	SET @formatid='1'
IF @Issuedate<>'' AND isnumeric(@Issuedate)=1
BEGIN
	SET @Issuedate=Cast(cast(@Issuedate as int)-2 as datetime)
	SET @Issuedate =convert(varchar(4),year(@Issuedate))+'-'+right('0'+ltrim(convert(varchar(2),month(@Issuedate))),2)+'-'+right('0'+ltrim(convert(varchar(2),day(@Issuedate))),2)
END
IF @StopDate<>'' AND isnumeric(@StopDate)=1
BEGIN
	SET @StopDate=Cast(cast(@StopDate as int)-2 as datetime)
	SET @StopDate =convert(varchar(4),year(@StopDate))+'-'+right('0'+ltrim(convert(varchar(2),month(@StopDate))),2)+'-'+right('0'+ltrim(convert(varchar(2),day(@StopDate))),2)
END

IF isdate(@Issuedate)=0
	SET @Issuedate =convert(varchar(4),year(getdate()))+'-'+right('0'+ltrim(convert(varchar(2),month(getdate()))),2)+'-'+right('0'+ltrim(convert(varchar(2),day(getdate()))),2)
IF isdate(@StopDate)=0
	SET @StopDate='2050-12-31'

	Declare @Stats1              	int
	Declare @Stats2	             	int
	Select @Stats1=stats From syscon where [order]=81
	Select @Stats2=stats  From syscon where [order]=82

	update syscon set [stats] =0 where [order]=81 or [order]=82

declare @AttributeId1 int,@AttributeId2 int,@AttributeId3 int,@AttributeId4 int,@AttributeId5 int,@AttributeId6 int,@AttributeId7 int,@AttributeId8 int


SELECT @newtypeid =typeid,@cspz=cspz FROM Ptype where fullname =@fullname and usercode =@usercode and deleted=0
BEGIN TRAN AAAAA
IF @newtypeid=''
BEGIN
	SET @re =0
	EXEC @re =FNimport_ANFzInsertP @parid,'ptype',@fullname,@name,@userCode,'','','',@Unit1,'',1,0,0,0,0,0,0,0,0,0,0,'',@returnPym,@Barcode,0,0,0,@formatid,0,@backRec output,0,0,0,0,1,0,0,0,0,0,@newtypeid output,@StopDate,'','',0,0,0,0,@Issuedate
	
	/*
	IF @re = -1
		RAISERROR('输入的父亲ID 号不存在',16,1)
	IF @re = -2
		RAISERROR('有相关数据存在',16,1)
	IF @re = -3
		RAISERROR('未取的儿子编码',16,1)
	IF @re = -4
 		RAISERROR('有相同的全名存在',16,1)
	IF @re = -5
	   	RAISERROR('有相同的编码存在',16,1)
	IF @re = -6
	        RAISERROR('有相同条码的数据存在',16,1)
	IF @re = -7
		RAISERROR('有相同编码和全名的数据存在',16,1)
	*/
	IF @newtypeid ='' OR @re<>0
	BEGIN

		GOTO Error
		
	END
	ELSE
	BEGIN
		CREATE TABLE #ColorName( [name] varchar(100))
		INSERT INTO #ColorName SELECT a From Fn_split(@colorName,',')
		INSERT INTO #ColorName SELECT a From Fn_split(@colorName,'，')
		DELETE FROM #ColorName WHERE [name] like '%,%'
		DELETE FROM #ColorName WHERE [name] like '%，%'

		
		CREATE TABLE #SizeName( [name] varchar(100))
		INSERT INTO #SizeName SELECT a From Fn_split(@SizeName,',')
		INSERT INTO #SizeName SELECT a From Fn_split(@SizeName,'，')
		DELETE FROM #SizeName WHERE [name] like '%,%'
		DELETE FROM #SizeName WHERE [name] like '%，%'
		Select @Qty=count(*)   FROM #ColorName a,Color b where a.[name]=b.[name]
		Select @Qty1=count(*)   FROM #SizeName a,Size b where a.[name]=b.[name]


		IF @Qty<>0 OR @Qty1<>0
		BEGIN		
			
			-- 写颜色
			IF @Qty<>0
			BEGIN
				DECLARE TT  CurSOR FOR  Select distinct Convert(varchar(10),(select top 1 colorid from color where [name]=a.[name])) as colorid  FROM #ColorName a
				OPEN TT
				FETCH NEXT FROM TT INTO @ColorID
				WHILE @@FETCH_STATUS =0
				BEGIN
					IF (NOT EXISTS(select top 1 1 from PtypeColor where colorid=@colorid and Ptypeid=@newtypeid)) AND @ColorID is not null
					BEGIN
						Update Ptype SET ColoridList =case when ColoridList='' then @ColorID else ColoridList+','+@ColorID end WHERE Typeid =@newtypeid
						INSERT INTO PtypeColor(ptypeid,colorid) select @newtypeid,@colorid
					END
					FETCH NEXT FROM TT INTO @ColorID
				END
				CLOSE TT
				DEALLOCATE TT
				DROP TABLE #ColorName
			END
			IF @Qty=0  -- 无色
			BEGIN
				UPDATE Ptype SET coloridlist='1'   WHERE  Typeid =@newtypeid 
				INSERT INTO PtypeColor(ptypeid,colorid) select @newtypeid,'1'
			END
			-- 写尺码
			IF @Qty1<>0
			BEGIN
				DECLARE TT  CurSOR FOR  Select distinct convert(varchar(10),(select top 1 sizeid from size where [name]=a.[name])) as sizeid  FROM #SizeName a
				OPEN TT
				FETCH NEXT FROM TT INTO @sizeid
				WHILE @@FETCH_STATUS =0
				BEGIN
					IF (NOT EXISTS(select top 1 1 from PtypeSize where sizeid=@sizeid and Ptypeid=@newtypeid))  AND @SizeID is not null
					BEGIN
						Update Ptype SET SizeidList = case when SizeidList='' then @SizeID else SizeidList+','+@SizeID end WHERE Typeid =@newtypeid
						INSERT INTO PtypeSize(ptypeid,Sizeid) select @newtypeid,@Sizeid
					END
					FETCH NEXT FROM TT INTO @sizeid
				END
				CLOSE TT
				DEALLOCATE TT
				DROP TABLE #SizeName
			END
			IF @Qty1=0  -- 无码
			BEGIN
				UPDATE Ptype SET sizeidlist='1'  WHERE  Typeid =@newtypeid 
				INSERT INTO PtypeSize(ptypeid,Sizeid) select @newtypeid,'1'
			END

			
			UPDATE Ptype SET cspz=0 WHERE sizeidlist<>'1' and coloridlist<>'1' AND Typeid =@newtypeid 
			UPDATE Ptype SET cspz=1 WHERE sizeidlist='1' and coloridlist<>'1'  AND Typeid =@newtypeid 
			UPDATE Ptype SET cspz=2 WHERE sizeidlist<>'1' and coloridlist='1'  AND Typeid =@newtypeid 
			UPDATE Ptype SET cspz=3 WHERE sizeidlist='1' and coloridlist='1'  AND Typeid =@newtypeid 
		END
		ELSE
		BEGIN --均色、均码
				UPDATE Ptype SET cspz=3,sizeidlist='1',coloridlist='1'   WHERE  Typeid =@newtypeid 
				INSERT INTO PtypeColor(ptypeid,colorid) select @newtypeid,'1'
				INSERT INTO PtypeSize(ptypeid,Sizeid) select @newtypeid,'1'
		END

		if exists(select c.[name],count(*) as qty from ptypecolor p,color c where p.ptypeid=@newtypeid and p.colorid=c.colorid group by c.[name] having(count(*))>1)
		BEGIN
			SET @re =-22
			goto error
		END
		if exists(select c.[barcode],count(*) as qty from ptypecolor p,color c where p.ptypeid=@newtypeid and p.colorid=c.colorid group by c.[barcode] having(count(*))>1)
		BEGIN
			SET @re =-23
			goto error
		END	
		if exists(select c.[name],count(*) as qty from ptypesize p,size c where p.ptypeid=@newtypeid and p.sizeid=c.sizeid group by c.[name] having(count(*))>1)
		BEGIN
			SET @re =-24
			goto error
		END
		if exists(select c.[barcode],count(*) as qty from ptypesize p,size c where p.ptypeid=@newtypeid and p.sizeid=c.sizeid group by c.[barcode] having(count(*))>1)
		BEGIN
			SET @re =-25
			goto error
		END	

			
		-- 价格
		IF @Tretailprice<>0
		EXEC fzWriteBasePrice 'LSSJ1',@newtypeid,@Tretailprice
		IF @Tpreprice1<>0
		EXEC fzWriteBasePrice 'YSSJ1',@newtypeid,@Tpreprice1
		IF @Tpreprice2<>0
		EXEC fzWriteBasePrice 'YSSJ2',@newtypeid,@Tpreprice2
		IF @Tpreprice3<>0
		EXEC fzWriteBasePrice 'YSSJ3',@newtypeid,@Tpreprice3
		IF @Tpreprice4<>0
		EXEC fzWriteBasePrice 'YSSJ4',@newtypeid,@Tpreprice4
		IF @Tdiscount1<>0
		EXEC fzWriteBasePrice 'YSZK1',@newtypeid,@Tdiscount1
		IF @Tdiscount2<>0
		EXEC fzWriteBasePrice 'YSZK2',@newtypeid,@Tdiscount2
		IF @Tdiscount3<>0
		EXEC fzWriteBasePrice 'YSZK3',@newtypeid,@Tdiscount3
		IF @Tdiscount4<>0
		EXEC fzWriteBasePrice 'YSZK4',@newtypeid,@Tdiscount4

		IF @Tbuyprice1<>0
		EXEC fzWriteBasePrice 'YSCGJ1',@newtypeid,@Tbuyprice1
		IF @Tbuyprice2<>0
		EXEC fzWriteBasePrice 'YSCGJ2',@newtypeid,@Tbuyprice2
		IF @Tbuydis1<>0
		EXEC fzWriteBasePrice 'YSCGZK1',@newtypeid,@Tbuydis1
		IF @Tbuydis1<>0
		EXEC fzWriteBasePrice 'YSCGZK2',@newtypeid,@Tbuydis2


		
		-- 写品牌
		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =1)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =1
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@category
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
		SET @AttributeId1 =@Attributeid

		-- 写季节

		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =2)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =2
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@season
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
		SET @AttributeId2 =@Attributeid
		
		-- 写辅助属性1
		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =3)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =3
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@FZ1
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
		SET @AttributeId3 =@Attributeid


		-- 写辅助属性2
		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =4)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =4
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@FZ2
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
		SET @AttributeId4 =@Attributeid
	
		-- 写辅助属性3
		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =5)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =5
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@FZ3
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
		SET @AttributeId5 =@Attributeid

		-- 写辅助属性4
		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =6)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =6
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@FZ4
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
		SET @AttributeId6 =@Attributeid

		-- 写辅助属性5
		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =7)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =7
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@FZ5
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
		SET @AttributeId7 =@Attributeid

		-- 写辅助属性6
		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =8)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =8
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@FZ6
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
		SET @AttributeId8 =@Attributeid

		--重新写系统码
		delete ptypebar where Ptypeid = @newtypeid  


		declare @barcodeT varchar(200)
		SET @barcodeT=''
		SELECT @sizeIdList=sizeIdList,@ColorIdList=ColorIdList,@barcodeT=ISNULL(barcode,'')	FROM Ptype where typeid = @newtypeid 
		if @barcodeT<>'' AND (Select Max(Sonnum) from Ptype where typeid = @newtypeid) = 0    
		BEGIN   
            EXEC GeneratePtypeBar 1,@newtypeid,@cspz,@BarcodeT,@ColorIdList,@SizeIdList,@AttributeId1,@AttributeId2,@AttributeId3,@AttributeId4,@AttributeId5,@AttributeId6,@AttributeId7,@AttributeId8,''     
		END


	END
END
ELSE
BEGIN
	SET @re =-5
	GOTO Error
END

--商品尺码组升级 cqhua
DECLARE @SizeIdlistTemp varchar(1000),@colorIdlistTemp varchar(1000)
DECLARE @sizelen int,@colorlen int
DECLARE @Ptypeid varchar(10)

SELECT @SizeIdlistTemp=sizeidlist,@sizelen=dbo.GetCharLen(sizeidlist,','),@ColorIdlistTemp=coloridlist,@Colorlen=dbo.GetCharLen(coloridlist,',')  from Ptype WHERE typeid=@newtypeid --AND sizeidlist<>'1' 


declare @UpdateTag INT
--商品尺码不包含在已有的尺码组中，新增尺码组
IF @SizeIdlistTemp='1'
	UPDATE Ptype SET sizegroupid =1 WHERE  typeid=@newtypeid AND sizegroupid =0 AND SizeidList ='1'
ELSE
BEGIN
	IF NOT EXISTS (select * FROM  (select distinct replace(','+dbo.GetSizeidlist(sizegroupid)+',',',,',',') as SizeIdlistOrder from SizeGroupRelation) X WHERE dbo.SizeListInclude(SizeIdlistOrder,@SizeIdlistTemp)=1 )
	BEGIN
		SET @UpdateTag=0
		EXEC [dbo].[XW_GetUpdateTag] 'SizeGroup', @UpdateTag OUTPUT
		INSERT INTO SizeGroup(name,remark,sysrow,[order],UpdateTag)  select (select '系统尺码组'+(select Convert(varchar(10),max(SizeGroupid)) from SizeGroup)) as name,'系统自动生成',0,10000,@UpdateTag
		INSERT INTO SizeGroupRelation(SizeGroupID,sizeid,rec,[order]) select @@identity,getid,0,iorder from  GetIdListTable(@SizeIdlistTemp)
	END

	UPDATE Ptype SET SizeGroupID = S.sizegroupid
	FROM Ptype p INNER JOIN  (select distinct sizegroupid,replace(','+dbo.GetSizeidlist(sizegroupid)+',',',,',',') as SizeIdlistOrder from SizeGroupRelation) S 
	ON dbo.SizeListInclude(S.SizeIdlistOrder,Sizeidlist)=1 
	WHERE P.typeid=@newtypeid  AND P.SizeGroupID=0 
END

----商品尺码不包含在已有的颜色组中，新增颜色组
--IF @colorIdlistTemp='1'
--	UPDATE Ptype SET colorgroupid =1 WHERE  typeid=@newtypeid AND colorgroupid =0 AND coloridList ='1'
--ELSE
--BEGIN
--	IF NOT EXISTS (select * FROM  (select distinct replace(','+dbo.GetColoridlist(colorgroupid)+',',',,',',') as colorIdlistOrder from colorGroupRelation) X WHERE dbo.SizeListInclude(colorIdlistOrder,@colorIdlistTemp)=1 )
--	BEGIN
--		SET @UpdateTag=0
--		EXEC [dbo].[XW_GetUpdateTag] 'ColorGroup', @UpdateTag OUTPUT
--		INSERT INTO colorGroup(name,remark,sysrow,[order],UpdateTag)  select (select '系统颜色组'+(select Convert(varchar(10),max(colorGroupid)) from colorGroup)) as name,'系统自动生成',0,10000,@UpdateTag
--		INSERT INTO colorGroupRelation(colorGroupID,colorid,rec,[order]) select @@identity,getid,0,iorder from  GetIdListTable(@colorIdlistTemp)
--	END

--	UPDATE Ptype SET colorGroupID = S.colorgroupid
--	FROM Ptype p INNER JOIN  (select distinct colorgroupid,replace(','+dbo.GetColoridlist(colorgroupid)+',',',,',',') as colorIdlistOrder from colorGroupRelation) S 
--	ON dbo.SizeListInclude(S.colorIdlistOrder,coloridlist)=1 
--	WHERE P.typeid=@newtypeid  --AND P.colorGroupID=0 
--END


COMMIT TRAN AAAAA
SET @outid =@newtypeid
	update syscon set [stats]=@Stats1 where [order]=81
	update syscon set [stats]=@Stats2 where [order]=82
RETURN 0
Error:
	IF @re=-1
		SET @outstr=' 数据库操作失败，请稍后重试！'
	
	IF @re=-2
		SET @outstr=' 此记录已经过账，不能再分类！'
	IF @re=-3
		SET @outstr=' 父亲ID号不存在！'
	IF @re=-4
		SET @outstr=' 系统行不允许修改！'
	IF @re=-5
		SET @outstr=' 该记录的编号或全名与其它记录相同'
	IF @re=-6
		SET @outstr=' 有相同条码的数据存在'
	IF @re=-7
		SET @outstr=' 有相同编码和全名的数据存在'
	IF @re=-17
		SET @outstr=' 颜色不存存在'
	IF @re=-18
		SET @outstr=' 尺码不存存在'
	IF @re=-22
		SET @outstr='同一商品中，不能存在名称相同的颜色'
	IF @re=-23
		SET @outstr='同一商品中，不能存在条码相同的颜色'
	IF @re=-24
		SET @outstr='同一商品中，不能存在名称相同的尺码'
	IF @re=-25
		SET @outstr='同一商品中，不能存在条码相同的尺码'

	IF @re=-108
		SET @outstr='盘点使用过'
	IF @re=-109
		SET @outstr='订单使用过'
	IF @re=-126
		SET @outstr='商品对照码存在'
	IF @re=-133
		SET @outstr='促销使用过'
	IF @re=-138
		SET @outstr='物价管理使用过'
	IF @re=-150
		SET @outstr='POS小票使用过'


	ROLLBACK TRAN AAAAA
	update syscon set [stats]=@Stats1 where [order]=81
	update syscon set [stats]=@Stats2 where [order]=82
	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].[FNimport_FzInsertP2]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FNimport_FzInsertP2]
GO








CREATE        PROCEDURE FNimport_FzInsertP2
(	
	@parid   varchar(50),
	@FullName 	varchar(66),                                             --父类ID
	@Name		varchar(30),                                             --商品简名4
	@UserCode 	varchar(26),                                             --用户编码5
	@Unit1 		varchar(8),                                               --商品单位1  9
	@Barcode	varchar(30),                                             --商品条码22
	@StopDate       varchar(10) ='',					 -- 停用日期
        @Issuedate 	varchar(10)='',						 -- 上市日期
	@colorname      varchar(1000),						 -- 颜色名称
	@sizename       varchar(1000),						 -- 尺码名称
    @category       varchar(100),                                             --品牌
	@season         varchar(100),                                             --季节
    @fz1       varchar(100),                                             --辅助属性1
    @fz2       varchar(100),                                             --辅助属性2
    @fz3       varchar(100),                                             --辅助属性3
    @fz4       varchar(100),                                             --辅助属性4
    @fz5       varchar(100),                                             --辅助属性5
    @fz6       varchar(100),                                             --辅助属性6
	@retailprice    varchar(20),		            			--零售价
	@preprice1 	varchar(20),                                         --预设售价1  13
	@preprice2 	varchar(20),                                         --预设售价2  14
	@preprice3 	varchar(20),                                         --预设售价3  15
	@preprice4 	varchar(20),                                         --预设售价4  16
	@discount1      varchar(20),
	@discount2      varchar(20),
	@discount3	varchar(20),
	@discount4	varchar(20),
	@prebuyprice1  varchar(20),
	@prebuyprice2  varchar(20),
	@prebuydis1  varchar(20),
	@prebuydis2  varchar(20),
	@outid          varchar(100) output,
	@outstr          varchar(200) output

) 
as 
SET NOCOUNT ON
DECLARE @newtypeid varchar(50)
SET @newtypeid=''
DECLARE @backRec int 
DECLARE @ColorID varchar(50)
DECLARE @SizeID varchar(50)
DECLARE @returnPym varchar(100)
DECLARE @errstr varchar(200)
SET @errstr =''
DECLARE @RE int
SET @RE =0
IF LTRIM(RTRIM(@FullName))=''
BEGIN
	SET @outstr='商品全名不能为空'
	RETURN -27
END

declare @ColorIdList varchar(1000)
declare @sizeIdList varchar(1000)

EXEC @re=FNimport_CheckChar @UserCode,@outstr output
IF @re<0
BEGIN
	return @re
END

EXEC @re=FNimport_CheckChar @FullName,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @Name,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @Unit1,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @Barcode,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @StopDate,@outstr output
IF @re<0
BEGIN
	return @re
END

EXEC @re=FNimport_CheckChar @Issuedate,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @colorname,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @sizename,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @category,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @season,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @fz1,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @fz2,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @fz3,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @fz4,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @fz5,@outstr output
IF @re<0
BEGIN
	return @re
END
EXEC @re=FNimport_CheckChar @fz6,@outstr output
IF @re<0
BEGIN
	return @re
END

/*
SET @parid=''
SELECT @parid =typeid from Ptype where fullname =@parFullname
IF @parid=''
BEGIN
	SET @errstr ='父类商品'+@parFullname+'不存在'
	RAISERROR(@errstr,16,1)
END
*/
IF LEN(@parid)=50
BEGIN
	SET @re =-10
	SET @outstr='超出系统允许的最大层数10'
	return @re
END

DECLARE	@Tretailprice   numeric(24,10)		            		--零售价
DECLARE	@Tpreprice1 	numeric(24,10)                                         --预设售价1  13
DECLARE	@Tpreprice2 	numeric(24,10)                                         --预设售价2  14
DECLARE	@Tpreprice3 	numeric(24,10)                                         --预设售价3  15
DECLARE	@Tpreprice4 	numeric(24,10)                                         --预设售价4  16
DECLARE	@Tdiscount1     numeric(24,10)
DECLARE @Tdiscount2      numeric(24,10)
DECLARE @Tdiscount3	numeric(24,10)
DECLARE @Tdiscount4	numeric(24,10)
DECLARE @Tbuyprice1	numeric(24,10)
DECLARE @Tbuyprice2	numeric(24,10)

DECLARE @Tbuydis1	numeric(24,10)
DECLARE @Tbuydis2	numeric(24,10)
DECLARE @typeid int
DECLARE @typeid1 int



IF ISNUMERIC(@retailprice)=0 
	SET @Tretailprice =0
ELSE
BEGIN
	SET @Tretailprice=Convert(numeric(24,2),@retailprice)
END
IF ISNUMERIC(@preprice1)=0 
	SET @Tpreprice1 =0
ELSE
    	SET @Tpreprice1=Convert(numeric(24,2),@preprice1)
IF ISNUMERIC(@preprice2)=0 
	SET @Tpreprice2 =0
ELSE
    	SET @Tpreprice2=Convert(numeric(24,2),@preprice2)
IF ISNUMERIC(@preprice3)=0 
	SET @Tpreprice3 =0
ELSE
    	SET @Tpreprice3=Convert(numeric(24,2),@preprice3)
IF ISNUMERIC(@preprice4)=0  
	SET @Tpreprice4 =0
ELSE
    	SET @Tpreprice4=Convert(numeric(24,2),@preprice4)

IF ISNUMERIC(@discount1)=0  
	SET @Tdiscount1 =0
ELSE
    	SET @Tdiscount1=Convert(numeric(24,2),@discount1)
IF ISNUMERIC(@discount2)=0  
	SET @Tdiscount2 =0
ELSE
    	SET @Tdiscount2=Convert(numeric(24,2),@discount2)
IF ISNUMERIC(@discount3)=0
	SET @Tdiscount3 =0
ELSE
    	SET @Tdiscount3=Convert(numeric(24,2),@discount3)
IF ISNUMERIC(@discount4)=0 
	SET @Tdiscount4 =0
ELSE
    	SET @Tdiscount4=Convert(numeric(24,2),@discount4)

IF ISNUMERIC(@prebuyprice1)=0 
	SET @Tbuyprice1 =0
ELSE
   	SET @Tbuyprice1=Convert(numeric(24,2),@prebuyprice1)

IF ISNUMERIC(@prebuyprice2)=0  
	SET @Tbuyprice2 =0
ELSE
   	SET @Tbuyprice2=Convert(numeric(24,2),@prebuyprice2)

IF ISNUMERIC(@prebuydis1)=0  
	SET @Tbuydis1 =0
ELSE
   	SET @Tbuydis1=Convert(numeric(24,2),@prebuydis1)

IF ISNUMERIC(@prebuydis2)=0 
	SET @Tbuydis2 =0
ELSE
   	SET @Tbuydis2=Convert(numeric(24,2),@prebuydis2)


IF @Tretailprice<0
	SET @Tretailprice =0

IF @Tpreprice1<0
	SET @Tpreprice1 =0

IF @Tpreprice2<0
	SET @Tpreprice2 =0
IF @Tpreprice3<0
	SET @Tpreprice3 =0
IF @Tpreprice4<0
	SET @Tpreprice4 =0

IF @Tdiscount1<0 OR @Tdiscount1>100
	SET @Tdiscount1 =0

IF @Tdiscount2<0 OR @Tdiscount2>100
	SET @Tdiscount2 =0
IF @Tdiscount3<0 OR @Tdiscount3>100
	SET @Tdiscount3 =0

IF @Tdiscount4<0 OR @Tdiscount4>100
	SET @Tdiscount4 =0

IF @Tbuyprice1<0
	SET @Tbuyprice1 =0


IF @Tbuyprice2<0
	SET @Tbuyprice2 =0
IF @Tbuydis1<0 OR @Tbuydis1>100
	SET @Tbuydis1 =0
IF @Tbuydis2<0 OR @Tbuydis2>100
	SET @Tbuydis2 =0


DECLARE @cspz int 
SET @cspz =-1 -- 3 颜色尺码都不需要

DECLARE @AssistTypeid varchar(10)
DECLARE @Attributeid varchar(10)
--SET @parid =@parFullname
EXEC @returnPym = FN_getPy @FullName

IF @UserCode=''
	SET @UserCode=left('New Add-'+@returnPym,26)

IF @parid=''
	SET @parid='00000'

DECLARE @formatid varchar(100)
SET @formatid='1'
SELECT @formatid =formatid FROM Ptype where typeid= @parid
IF @formatid=''
	SET @formatid='1'
SELECT @newtypeid =typeid,@cspz=cspz FROM Ptype where fullname =@fullname and usercode =@usercode and deleted=0

IF @Issuedate<>'' AND isnumeric(@Issuedate)=1
BEGIN
	SET @Issuedate=Cast(cast(@Issuedate as int)-2 as datetime)
	SET @Issuedate =convert(varchar(4),year(@Issuedate))+'-'+right('0'+ltrim(convert(varchar(2),month(@Issuedate))),2)+'-'+right('0'+ltrim(convert(varchar(2),day(@Issuedate))),2)
END
IF @StopDate<>'' AND isnumeric(@StopDate)=1
BEGIN
	SET @StopDate=Cast(cast(@StopDate as int)-2 as datetime)
	SET @StopDate =convert(varchar(4),year(@StopDate))+'-'+right('0'+ltrim(convert(varchar(2),month(@StopDate))),2)+'-'+right('0'+ltrim(convert(varchar(2),day(@StopDate))),2)
END

IF @formatid='' or  @formatid='1'
	SET @formatid='1'
IF isdate(@Issuedate)=0
	SET @Issuedate =convert(varchar(4),year(getdate()))+'-'+right('0'+ltrim(convert(varchar(2),month(getdate()))),2)+'-'+right('0'+ltrim(convert(varchar(2),day(getdate()))),2)
IF isdate(@StopDate)=0
	SET @StopDate='2050-12-31'

	Declare @Stats1              	int
	Declare @Stats2	             	int
	Select @Stats1=stats From syscon where [order]=81
	Select @Stats2=stats  From syscon where [order]=82

	update syscon set [stats] =0 where [order]=81 or [order]=82

declare @AttributeId1 int,@AttributeId2 int,@AttributeId3 int,@AttributeId4 int,@AttributeId5 int,@AttributeId6 int,@AttributeId7 int,@AttributeId8 int
BEGIN TRAN AAAAA
IF @newtypeid<>''
BEGIN
	SET @ColorID=''
	select @ColorID=colorid from color where [Name]=@colorname	
	SET @SizeID=''
	select @SizeID=sizeid from size where [Name]=@sizename	

	IF @colorname='' OR @ColorID=''
		SET @ColorID ='1'
	IF @sizename='' OR @SizeID=''
		SET @SizeID ='1'
	
	IF (@ColorID<>'' OR @SizeID<>'')
	BEGIN
		--Update Ptype SET ColoridList =ColoridList+','+@ColorID,SizeidList =SizeidList+','+@SizeID WHERE Typeid =@newtypeid
		IF EXISTS(select top 1 1 from PtypeColor where colorid=@colorid and Ptypeid=@newtypeid  ) AND EXISTS (select top 1 1 from PtypeSize where sizeid=@sizeid and Ptypeid=@newtypeid)
		BEGIN
			SET @re =-26
			GOTO error
		END
		
		IF (@ColorID<>'1' AND  EXISTS(select top 1 1 from PtypeColor where Ptypeid=@newtypeid AND Colorid='1'))
		BEGIN
			SET @re =-19
			goto error
		END 
		
		IF (@sizeid<>'1' AND EXISTS(select top 1 1 from PtypeSize where Ptypeid=@newtypeid AND Sizeid='1'))
		BEGIN
			SET @re =-20
			goto error
		END 
		
		IF NOT EXISTS(select top 1 1 from PtypeColor where colorid=@colorid and Ptypeid=@newtypeid) AND ((@ColorID='1' AND NOT EXISTS(select top 1 1 from PtypeColor where Ptypeid=@newtypeid)) OR (@ColorID<>'1' AND NOT EXISTS(select top 1 1 from PtypeColor where Ptypeid=@newtypeid AND Colorid='1')))
		BEGIN
			Update Ptype SET ColoridList =case when ColoridList='' then @ColorID else ColoridList+','+@ColorID end WHERE Typeid =@newtypeid
			INSERT INTO PtypeColor(ptypeid,colorid) select @newtypeid,@colorid
		END

		IF NOT EXISTS(select top 1 1 from PtypeSize where sizeid=@sizeid and Ptypeid=@newtypeid)  AND ((@sizeid='1' AND NOT EXISTS(select top 1 1 from PtypeSize where Ptypeid=@newtypeid)) OR (@sizeid<>'1' AND NOT EXISTS(select top 1 1 from PtypeSize where Ptypeid=@newtypeid AND Sizeid='1')))
		BEGIN
			INSERT INTO PtypeSize(ptypeid,Sizeid) select @newtypeid,@Sizeid
			Update Ptype SET SizeidList = case when SizeidList='' then @SizeID else SizeidList+','+@SizeID end WHERE Typeid =@newtypeid
		END

		if exists(select c.[name],count(*) as qty from ptypecolor p,color c where p.ptypeid=@newtypeid and p.colorid=c.colorid group by c.[name] having(count(*))>1)
		BEGIN
			SET @re =-22
			goto error
		END
		if exists(select c.[barcode],count(*) as qty from ptypecolor p,color c where p.ptypeid=@newtypeid and p.colorid=c.colorid group by c.[barcode] having(count(*))>1)
		BEGIN
			SET @re =-23
			goto error
		END	
		if exists(select c.[name],count(*) as qty from ptypesize p,size c where p.ptypeid=@newtypeid and p.sizeid=c.sizeid group by c.[name] having(count(*))>1)
		BEGIN
			SET @re =-24
			goto error
		END
		if exists(select c.[barcode],count(*) as qty from ptypesize p,size c where p.ptypeid=@newtypeid and p.sizeid=c.sizeid group by c.[barcode] having(count(*))>1)
		BEGIN
			SET @re =-25
			goto error
		END	
	END
	ELSE
	BEGIN
		SET @re =-21
		goto error
	END 
	update ptype set cspz=0 where coloridlist<>'' and coloridlist<>'1' and sizeidlist<>'' and sizeidlist<>'1' --颜色尺码都需要
	update ptype set cspz=1 where coloridlist<>'' and coloridlist<>'1' and sizeidlist<>'' and sizeidlist='1' --只要颜色
	update ptype set cspz=2 where coloridlist<>'' and coloridlist='1' and sizeidlist<>'' and sizeidlist<>'1' --只要尺码
	update ptype set cspz=3 where coloridlist<>'' and coloridlist='1' and sizeidlist<>'' and sizeidlist='1' --颜色尺码都不需要

	--不同行时，对于同一商品的不同颜色尺码行，只处理颜色尺码，其它的不处理 ，所以下面屏蔽掉


	/*
	IF @Tretailprice<>0 AND NOT EXISTS(Select top 1 1 from PtypePrice where ptypeid=@newtypeid AND PriceTypeid='LSSJ1')
	EXEC fzWriteBasePrice 'LSSJ1',@newtypeid,@Tretailprice
	IF @Tpreprice1<>0 AND NOT EXISTS(Select top 1 1 from PtypePrice where ptypeid=@newtypeid AND PriceTypeid='YSSJ1')
	EXEC fzWriteBasePrice 'YSSJ1',@newtypeid,@Tpreprice1
	IF @Tpreprice2<>0 AND NOT EXISTS(Select top 1 1 from PtypePrice where ptypeid=@newtypeid AND PriceTypeid='YSSJ2')
	EXEC fzWriteBasePrice 'YSSJ2',@newtypeid,@Tpreprice2
	IF @Tpreprice3<>0 AND NOT EXISTS(Select top 1 1 from PtypePrice where ptypeid=@newtypeid AND PriceTypeid='YSSJ3')
	EXEC fzWriteBasePrice 'YSSJ3',@newtypeid,@Tpreprice3
	IF @Tpreprice4<>0 AND NOT EXISTS(Select top 1 1 from PtypePrice where ptypeid=@newtypeid AND PriceTypeid='YSSJ4')
	EXEC fzWriteBasePrice 'YSSJ4',@newtypeid,@Tpreprice4
	IF @Tdiscount1<>0 AND NOT EXISTS(Select top 1 1 from PtypePrice where ptypeid=@newtypeid AND PriceTypeid='YSZK1')
	EXEC fzWriteBasePrice 'YSZK1',@newtypeid,@Tdiscount1
	IF @Tdiscount2<>0 AND NOT EXISTS(Select top 1 1 from PtypePrice where ptypeid=@newtypeid AND PriceTypeid='YSZK2')
	EXEC fzWriteBasePrice 'YSZK2',@newtypeid,@Tdiscount2
	IF @Tdiscount3<>0 AND NOT EXISTS(Select top 1 1 from PtypePrice where ptypeid=@newtypeid AND PriceTypeid='YSZK3')
	EXEC fzWriteBasePrice 'YSZK3',@newtypeid,@Tdiscount3
	IF @Tdiscount4<>0 AND NOT EXISTS(Select top 1 1 from PtypePrice where ptypeid=@newtypeid AND PriceTypeid='YSZK4')
	EXEC fzWriteBasePrice 'YSZK4',@newtypeid,@Tdiscount4
	
	IF @Tbuyprice1<>0  AND NOT EXISTS(Select top 1 1 from PtypePrice where ptypeid=@newtypeid AND PriceTypeid='YSCGJ1')
	EXEC fzWriteBasePrice 'YSCGJ1',@newtypeid,@Tbuyprice1
	IF @Tbuyprice2<>0  AND NOT EXISTS(Select top 1 1 from PtypePrice where ptypeid=@newtypeid AND PriceTypeid='YSCGJ2')
	EXEC fzWriteBasePrice 'YSCGJ2',@newtypeid,@Tbuyprice2
	IF @Tbuydis1<>0  AND NOT EXISTS(Select top 1 1 from PtypePrice where ptypeid=@newtypeid AND PriceTypeid='YSCGZK1')
	EXEC fzWriteBasePrice 'YSCGZK1',@newtypeid,@Tbuydis1
	IF @Tbuydis1<>0 AND NOT EXISTS(Select top 1 1 from PtypePrice where ptypeid=@newtypeid AND PriceTypeid='YSCGZK2')
	EXEC fzWriteBasePrice 'YSCGZK2',@newtypeid,@Tbuydis2



	

	-- 写品牌
	SET @AssistTypeid=''
	SET @Attributeid=''
	IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =1)
		select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =1
	IF @AssistTypeid<>'' 
	BEGIN
		select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@category

		
		IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid) 
		AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
		insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
	END


	-- 写季节
	SET @AssistTypeid=''
	SET @Attributeid=''
	IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =2)
		select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =2
	IF @AssistTypeid<>'' 
	BEGIN
		select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@season
		IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
		AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
		insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
	END
	

	-- 写辅助属性1
	SET @AssistTypeid=''
	SET @Attributeid=''
	IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =3)
		select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =3
	IF @AssistTypeid<>'' 
	BEGIN
		select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@fz1
		IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
		AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
		insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
	END

	-- 写辅助属性2
	SET @AssistTypeid=''
	SET @Attributeid=''
	IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =4)
		select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =4
	IF @AssistTypeid<>'' 
	BEGIN
		select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@fz2
		IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
		AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
		insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
	END

	-- 写辅助属性3
	SET @AssistTypeid=''
	SET @Attributeid=''
	IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =5)
		select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =5
	IF @AssistTypeid<>'' 
	BEGIN
		select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@fz3
		IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
		AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
		insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
	END
	-- 写辅助属性4
	SET @AssistTypeid=''
	SET @Attributeid=''
	IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =6)
		select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =6
	IF @AssistTypeid<>'' 
	BEGIN
		select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@fz4
		IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
		AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
		insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
	END
	-- 写辅助属性5
	SET @AssistTypeid=''
	SET @Attributeid=''
	IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =7)
		select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =7
	IF @AssistTypeid<>'' 
	BEGIN
		select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@fz5
		IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
		AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
		insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
	END
	-- 写辅助属性6
	SET @AssistTypeid=''
	SET @Attributeid=''
	IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =8)
		select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =8
	IF @AssistTypeid<>'' 
	BEGIN
		select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@fz6
		IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
		AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
		insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
	END
	*/
	--重新写系统码
	delete ptypebar where Ptypeid = @newtypeid  

	declare @barcodeT2 varchar(200)
	SET @barcodeT2=''
	SELECT @sizeIdList=sizeIdList,@ColorIdList=ColorIdList,@barcodeT2=ISNULL(barcode,'') FROM Ptype where typeid = @newtypeid 
	if @barcodeT2<>'' AND (Select Max(Sonnum) from Ptype where typeid = @newtypeid) = 0    
	BEGIN   
		select a.typeid,P.AttributeId INTO #PtypeAttribute From PtypeAttribute p ,AssistAttribute A where  p.ptypeid=@newtypeid and p.attributeid =a.attributeid

		select @AttributeId1=isnull(AttributeId,0) From #PtypeAttribute WHERE Typeid=1
		select @AttributeId2=isnull(AttributeId,0) From #PtypeAttribute WHERE Typeid=2
		select @AttributeId3=isnull(AttributeId,0) From #PtypeAttribute WHERE Typeid=3
		select @AttributeId4=isnull(AttributeId,0) From #PtypeAttribute WHERE Typeid=4
		select @AttributeId5=isnull(AttributeId,0) From #PtypeAttribute WHERE Typeid=5
		select @AttributeId6=isnull(AttributeId,0) From #PtypeAttribute WHERE Typeid=6
		select @AttributeId7=isnull(AttributeId,0) From #PtypeAttribute WHERE Typeid=7
		select @AttributeId8=isnull(AttributeId,0) From #PtypeAttribute WHERE Typeid=8
		
		IF @AttributeId1 is null
		set @AttributeId1  =0
		IF @AttributeId2 is null
		set @AttributeId2  =0
		IF @AttributeId3 is null
		set @AttributeId3  =0
		IF @AttributeId4 is null
		set @AttributeId4  =0
		IF @AttributeId5 is null
		set @AttributeId5  =0
		IF @AttributeId6 is null
		set @AttributeId6  =0
		IF @AttributeId7 is null
		set @AttributeId7  =0
		IF @AttributeId8 is null
		set @AttributeId8  =0
		SELECT @cspz=cspz FROM Ptype where @newtypeid =typeid
		
		DROP TABLE   #PtypeAttribute
        EXEC GeneratePtypeBar 1,@newtypeid,@cspz,@BarcodeT2,@ColorIdList,@SizeIdList,@AttributeId1,@AttributeId2,@AttributeId3,@AttributeId4,@AttributeId5,@AttributeId6,@AttributeId7,@AttributeId8,''     
	END


END
ELSE
BEGIN
	SET @re =0
	EXEC @re =FNimport_ANFzInsertP @parid,'ptype',@fullname,@name,@userCode,'','','',@Unit1,'',1,0,0,0,0,0,0,0,0,0,0,'',@returnPym,@Barcode,0,0,0,@formatid,0,@backRec output,0,0,0,0,1,0,0,0,0,0,@newtypeid output,@StopDate,'','',0,0,0,0,@Issuedate
	
	/*
	IF @re = -1
		RAISERROR('输入的父亲ID 号不存在',16,1)
	IF @re = -2
		RAISERROR('有相关数据存在',16,1)
	IF @re = -3
		RAISERROR('未取的儿子编码',16,1)
	IF @re = -4
 		RAISERROR('有相同的全名存在',16,1)
	IF @re = -5
	   	RAISERROR('有相同的编码存在',16,1)
	IF @re = -6
	        RAISERROR('有相同条码的数据存在',16,1)
	IF @re = -7
		RAISERROR('有相同编码和全名的数据存在',16,1)
	*/
	IF @newtypeid ='' OR @re<>0
	BEGIN
	
		GOTO Error
		
	END
	ELSE
	BEGIN
		IF @Tretailprice<>0
		EXEC fzWriteBasePrice 'LSSJ1',@newtypeid,@Tretailprice
		IF @Tpreprice1<>0
		EXEC fzWriteBasePrice 'YSSJ1',@newtypeid,@Tpreprice1
		IF @Tpreprice2<>0
		EXEC fzWriteBasePrice 'YSSJ2',@newtypeid,@Tpreprice2
		IF @Tpreprice3<>0
		EXEC fzWriteBasePrice 'YSSJ3',@newtypeid,@Tpreprice3
		IF @Tpreprice4<>0
		EXEC fzWriteBasePrice 'YSSJ4',@newtypeid,@Tpreprice4
		IF @Tdiscount1<>0
		EXEC fzWriteBasePrice 'YSZK1',@newtypeid,@Tdiscount1
		IF @Tdiscount2<>0
		EXEC fzWriteBasePrice 'YSZK2',@newtypeid,@Tdiscount2
		IF @Tdiscount3<>0
		EXEC fzWriteBasePrice 'YSZK3',@newtypeid,@Tdiscount3
		IF @Tdiscount4<>0
		EXEC fzWriteBasePrice 'YSZK4',@newtypeid,@Tdiscount4

		IF @Tbuyprice1<>0
		EXEC fzWriteBasePrice 'YSCGJ1',@newtypeid,@Tbuyprice1
		IF @Tbuyprice2<>0
		EXEC fzWriteBasePrice 'YSCGJ2',@newtypeid,@Tbuyprice2
		IF @Tbuydis1<>0
		EXEC fzWriteBasePrice 'YSCGZK1',@newtypeid,@Tbuydis1
		IF @Tbuydis1<>0
		EXEC fzWriteBasePrice 'YSCGZK2',@newtypeid,@Tbuydis2



		SET @ColorID=''
		select @ColorID=colorid from color where [Name]=@colorname
		SET @SizeID=''
		select @SizeID=sizeid from size where [Name]=@sizename	
		
		IF @colorname='' OR @ColorID=''
			SET @ColorID ='1'
		IF @sizename='' OR @sizeid=''
			SET @sizeid='1'
			
		IF (@ColorID<>'' OR @SizeID<>'')
		BEGIN

			IF NOT EXISTS(select top 1 1 from PtypeColor where colorid=@colorid and Ptypeid=@newtypeid)
			begin
				IF @colorid='1'
				BEGIN
					Update Ptype SET ColoridList =@colorid WHERE Typeid =@newtypeid
					DELETE FROM PtypeColor WHERE  pTypeid =@newtypeid
					INSERT INTO PtypeColor(ptypeid,colorid) select @newtypeid,@colorid
				END
				ELSE
				BEGIN
					IF NOT EXISTS(select top 1 1 from PtypeColor where colorid='1' and Ptypeid=@newtypeid)
					BEGIN
						Update Ptype SET ColoridList =case when ColoridList='' then @ColorID else   ColoridList+','+@ColorID end  WHERE Typeid =@newtypeid
						INSERT INTO PtypeColor(ptypeid,colorid) select @newtypeid,@colorid
					END
				END
			end
			IF NOT EXISTS(select top 1 1 from PtypeSize where sizeid=@sizeid and Ptypeid=@newtypeid)
			BEGIN
				IF @SizeID ='1'
				BEGIN
					Update Ptype SET SizeidList =@SizeID WHERE Typeid =@newtypeid
					DELETE FROM  PtypeSize where Ptypeid=@newtypeid
					INSERT INTO PtypeSize(ptypeid,Sizeid) select @newtypeid,@Sizeid
				END
				ELSE
				BEGIN
					IF NOT EXISTS(select top 1 1 from PtypeSize where sizeid='1' and Ptypeid=@newtypeid)
					BEGIN
						Update Ptype SET SizeidList = case when SizeidList='' then @SizeID else SizeidList+','+@SizeID end WHERE Typeid =@newtypeid
						INSERT INTO PtypeSize(ptypeid,Sizeid) select @newtypeid,@Sizeid
					END
				END
			END
			
			
		END
		ELSE
		BEGIN
			SET @re =-21
			goto error
		END
		update ptype set cspz=0 where coloridlist<>'' and coloridlist<>'1' and sizeidlist<>'' and sizeidlist<>'1' --颜色尺码都需要
		update ptype set cspz=1 where coloridlist<>'' and coloridlist<>'1' and sizeidlist<>'' and sizeidlist='1' --只要颜色
		update ptype set cspz=2 where coloridlist<>'' and coloridlist='1' and sizeidlist<>'' and sizeidlist<>'1' --只要尺码
		update ptype set cspz=3 where coloridlist<>'' and coloridlist='1' and sizeidlist<>'' and sizeidlist='1' --颜色尺码都不需要
		-- 写品牌
		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =1)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =1
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@category
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
		SET @AttributeId8 =@Attributeid
	
		-- 写季节
		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =2)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =2
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@season
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
		
	
		-- 写辅助属性1
		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =3)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =3
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@fz1
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
	
		-- 写辅助属性2
		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =4)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =4
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@fz2
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
	
		-- 写辅助属性3
		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =5)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =5
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@fz3
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
		-- 写辅助属性4
		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =6)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =6
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@fz4
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
		-- 写辅助属性5
		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =7)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =7
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@fz5
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
		-- 写辅助属性6
		SET @AssistTypeid=''
		SET @Attributeid=''
		IF EXISTS(Select top 1 1 from AssistType where choose =1 and typeorder =8)
			select @AssistTypeid=typeid from AssistType where choose =1 and typeorder =8
		IF @AssistTypeid<>'' 
		BEGIN
			select @Attributeid=Attributeid,@typeid=typeid from AssistAttribute where typeid=@AssistTypeid AND UserName =@fz6
			IF @Attributeid<>'' AND NOT EXISTS(select * from ptypeattribute where ptypeid=@newtypeid and attributeid=@Attributeid)
			AND NOT EXISTS(select * from ptypeattribute  a, AssistAttribute b where a.ptypeid=@newtypeid and a.attributeid=b.attributeid and b.typeid=@typeid )
			insert into ptypeattribute(ptypeid,attributeid) values(@newtypeid,@Attributeid)
		END
		--重新写系统码
		delete ptypebar where Ptypeid = @newtypeid  

		declare @barcodeT varchar(200)
		SET @barcodeT=''
		SELECT @sizeIdList=sizeIdList,@ColorIdList=ColorIdList,@barcodeT=ISNULL(barcode,'') FROM Ptype where typeid = @newtypeid 
		if @barcodeT<>'' AND (Select Max(Sonnum) from Ptype where typeid = @newtypeid) = 0    
		BEGIN   
			select a.typeid,P.AttributeId INTO #PtypeAttribute1 From PtypeAttribute p ,AssistAttribute A where  p.ptypeid=@newtypeid and p.attributeid =a.attributeid
			
		select @AttributeId1=isnull(AttributeId,0) From #PtypeAttribute1 WHERE Typeid=1
		select @AttributeId2=isnull(AttributeId,0) From #PtypeAttribute1 WHERE Typeid=2
		select @AttributeId3=isnull(AttributeId,0) From #PtypeAttribute1 WHERE Typeid=3
		select @AttributeId4=isnull(AttributeId,0) From #PtypeAttribute1 WHERE Typeid=4
		select @AttributeId5=isnull(AttributeId,0) From #PtypeAttribute1 WHERE Typeid=5
		select @AttributeId6=isnull(AttributeId,0) From #PtypeAttribute1 WHERE Typeid=6
		select @AttributeId7=isnull(AttributeId,0) From #PtypeAttribute1 WHERE Typeid=7
		select @AttributeId8=isnull(AttributeId,0) From #PtypeAttribute1 WHERE Typeid=8
		
		IF @AttributeId1 is null
		set @AttributeId1  =0
		IF @AttributeId2 is null
		set @AttributeId2  =0
		IF @AttributeId3 is null
		set @AttributeId3  =0
		IF @AttributeId4 is null
		set @AttributeId4  =0
		IF @AttributeId5 is null
		set @AttributeId5  =0
		IF @AttributeId6 is null
		set @AttributeId6  =0
		IF @AttributeId7 is null
		set @AttributeId7  =0
		IF @AttributeId8 is null
		set @AttributeId8  =0
		SELECT @cspz=cspz FROM Ptype where @newtypeid =typeid
		
			DROP TABLE   #PtypeAttribute1
	        EXEC GeneratePtypeBar 1,@newtypeid,@cspz,@BarcodeT,@ColorIdList,@SizeIdList,@AttributeId1,@AttributeId2,@AttributeId3,@AttributeId4,@AttributeId5,@AttributeId6,@AttributeId7,@AttributeId8,''     
		   
		END
		
	END
END

--商品尺码组升级 cqhua
DECLARE @SizeIdlistTemp varchar(1000),@colorIdlistTemp varchar(1000)
DECLARE @sizelen int,@colorlen int
DECLARE @Ptypeid varchar(10)

SELECT @SizeIdlistTemp=sizeidlist,@sizelen=dbo.GetCharLen(sizeidlist,','),@ColorIdlistTemp=coloridlist,@Colorlen=dbo.GetCharLen(coloridlist,',')  from Ptype WHERE typeid=@newtypeid-- AND sizeidlist<>'1' 


declare @UpdateTag INT
--商品尺码不包含在已有的尺码组中，新增尺码组
IF @SizeIdlistTemp='1'
	UPDATE Ptype SET sizegroupid =1 WHERE  typeid=@newtypeid AND sizegroupid =0 AND SizeidList ='1'
ELSE
BEGIN
	IF NOT EXISTS (select * FROM  (select distinct replace(','+dbo.GetSizeidlist(sizegroupid)+',',',,',',') as SizeIdlistOrder from SizeGroupRelation) X WHERE dbo.SizeListInclude(SizeIdlistOrder,@SizeIdlistTemp)=1 )
	BEGIN
		SET @UpdateTag=0
		EXEC [dbo].[XW_GetUpdateTag] 'SizeGroup', @UpdateTag OUTPUT
		INSERT INTO SizeGroup(name,remark,sysrow,[order],UpdateTag)  select (select '系统尺码组'+(select Convert(varchar(10),max(SizeGroupid)) from SizeGroup)) as name,'系统自动生成',0,10000,@UpdateTag
		INSERT INTO SizeGroupRelation(SizeGroupID,sizeid,rec,[order]) select @@identity,getid,0,iorder from  GetIdListTable(@SizeIdlistTemp)
	END

	UPDATE Ptype SET SizeGroupID = S.sizegroupid
	FROM Ptype p INNER JOIN  (select distinct sizegroupid,replace(','+dbo.GetSizeidlist(sizegroupid)+',',',,',',') as SizeIdlistOrder from SizeGroupRelation) S 
	ON dbo.SizeListInclude(S.SizeIdlistOrder,Sizeidlist)=1 
	WHERE P.typeid=@newtypeid  --AND P.SizeGroupID=0 
END

----商品尺码不包含在已有的颜色组中，新增颜色组
--IF @colorIdlistTemp='1'
--	UPDATE Ptype SET colorgroupid =1 WHERE  typeid=@newtypeid AND colorgroupid =0 AND coloridList ='1'
--ELSE
--BEGIN
--	IF NOT EXISTS (select * FROM  (select distinct replace(','+dbo.Getcoloridlist(colorgroupid)+',',',,',',') as colorIdlistOrder from colorGroupRelation) X WHERE dbo.SizeListInclude(colorIdlistOrder,@colorIdlistTemp)=1 )
--	BEGIN
--		SET @UpdateTag=0
--		EXEC [dbo].[XW_GetUpdateTag] 'ColorGroup', @UpdateTag OUTPUT
--		INSERT INTO colorGroup(name,remark,sysrow,[order],UpdateTag)  select (select '系统颜色组'+(select Convert(varchar(10),max(colorGroupid)) from colorGroup)) as name,'系统自动生成',0,10000,@UpdateTag
--		INSERT INTO colorGroupRelation(colorGroupID,colorid,rec,[order]) select @@identity,getid,0,iorder from  GetIdListTable(@colorIdlistTemp)
--	END

--	UPDATE Ptype SET colorGroupID = S.colorgroupid
--	FROM Ptype p INNER JOIN  (select distinct colorgroupid,replace(','+dbo.Getcoloridlist(colorgroupid)+',',',,',',') as colorIdlistOrder from colorGroupRelation) S 
--	ON dbo.SizeListInclude(S.colorIdlistOrder,coloridlist)=1 
--	WHERE P.typeid=@newtypeid  --AND P.colorGroupID=0 
--END

COMMIT TRAN AAAAA
SET @outid =@newtypeid
	update syscon set [stats]=@Stats1 where [order]=81
	update syscon set [stats]=@Stats2 where [order]=82
RETURN 0
Error:
	IF @re=-1
		SET @outstr=' 数据库操作失败，请稍后重试！'
	
	IF @re=-2
		SET @outstr=' 此记录已经过账，不能再分类！'
	IF @re=-3
		SET @outstr=' 父亲ID号不存在！'
	IF @re=-4
		SET @outstr=' 系统行不允许修改！'
	IF @re=-5
		SET @outstr=' 该记录的编号或全名与其它记录相同'
	IF @re=-6
		SET @outstr=' 有相同条码的数据存在'
	IF @re=-17
		SET @outstr=' 颜色不存存在'
	IF @re=-18
		SET @outstr=' 尺码不存存在'
	IF @re=-19
		SET @outstr=' 颜色不能与均色同时存在'
	IF @re=-20
		SET @outstr=' 尺码不能与均码同时存在'
	IF @re=-20
		SET @outstr=' 尺码或颜色不存在'
	IF @re=-21
		SET @outstr=' 尺码或颜色都不存在'
	IF @re=-22
		SET @outstr='同一商品中，不能存在名称相同的颜色'
	IF @re=-23
		SET @outstr='同一商品中，不能存在条码相同的颜色'
	IF @re=-24
		SET @outstr='同一商品中，不能存在名称相同的尺码'
	IF @re=-25
		SET @outstr='同一商品中，不能存在条码相同的尺码'
	IF @re=-26
		SET @outstr='相同颜色、尺码的商品已导入过'

	IF @re=-108
		SET @outstr='盘点使用过'
	IF @re=-109
		SET @outstr='订单使用过'
	IF @re=-126
		SET @outstr='商品对照码存在'
	IF @re=-133
		SET @outstr='促销使用过'
	IF @re=-138
		SET @outstr='物价管理使用过'
	IF @re=-150
		SET @outstr='POS小票使用过'
	ROLLBACK TRAN AAAAA
	update syscon set [stats]=@Stats1 where [order]=81
	update syscon set [stats]=@Stats2 where [order]=82
	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].[FZInsertColorSizeGroup]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZInsertColorSizeGroup]
GO

--  ********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：F_B_InsertColorSizeGroup                                       
--  ||   过程功能：写颜色、尺码组表  
--  ||=========================================================================================  
--  ||   参数说明：  参数名称         类型            意义                     输入输出  
--  ||            -----------------------------------------------------------------------------  
--  ||               @cMode  varchar(1),                            --A为：增加，M：为修改，D：为删除  
--  ||               @tablename  varchar(20),                     --表名'CG:颜色组、SG:尺码组'  
--  ||               @name  varchar(30),                            --颜色组或尺码组的组名  
--  ||               @remark  varchar(100),                        --用户说明  
--  ||               @CSgroupid  int      output                     --旧的颜色组或尺码组ID号  
--  ||=========================================================================================     
--  ||   返回值：         值                                     说明  
--  ||       ----------------------------------------------------------------------------------------  
--  ||                    0                                 执行成功  
--  ||                     －1                            插入颜色组主表失败  
--  ||              －2         更新颜色组主表失败  
--  ||  －3                            插入尺码组主表失败  
--  ||  －4         更新尺码组主表失败  
--  ||  －5         有相同的颜色组存在  
--  ||  －6         有相同的尺码组存在  
--  ||  －7          该尺码、颜色组正在使用不能修改或删除  
--  ||==========================================================================================  

/*
cqhua 2011-8-29
尺码组使用过，不能删除
*/

CREATE  PROCEDURE FZInsertColorSizeGroup
    (
      @cMode VARCHAR(2) ,                            --A为：增加，M：为修改，D：为删除  
      @tablename VARCHAR(20) ,                     --表名'CG:颜色组、SG:尺码组'  
      @name VARCHAR(30) ,                            --颜色组或尺码组的组名  
      @remark VARCHAR(100) ,                        --用户说明  
      @CSgroupid INT OUTPUT ,                     --旧的颜色组或尺码组ID号  
      @SysRow INT = 0  --是否是系统行s  
    )
AS 
    DECLARE @cgd INT ,
        @sgd VARCHAR(30) ,
        @oldbar VARCHAR(30)  
    DECLARE @oldBcon VARCHAR(30) ,
        @ptypeid VARCHAR(50) ,
        @formatid VARCHAR(10) ,
        @oobarcode VARCHAR(30)   
    DECLARE @oldCGid INT ,
        @oldSGid INT ,
        @cid INT     
    DECLARE @colorid INT ,
        @cbar VARCHAR(10) ,
        @sieeid INT ,
        @sbar VARCHAR(10) ,
        @bar VARCHAR(50)         

    DECLARE @UpdateTag INT

    IF @tablename = 'CG' 
        BEGIN     
            IF @cMode = 'A' 
                BEGIN   
                    IF EXISTS ( SELECT  colorgroupid
                                FROM    colorgroup
                                WHERE   colorgroupid NOT IN ( SELECT DISTINCT
                                                              colorgroupid
                                                              FROM
                                                              ptype )
                                        AND sysrow = 1
                                        AND colorgroupid <> 1 ) 
                        BEGIN  
                            DELETE  colorgroup
                            WHERE   colorgroupid NOT IN ( SELECT DISTINCT
                                                              colorgroupid
                                                          FROM
                                                              ptype )
                                    AND sysrow = 1
                                    AND colorgroupid <> 1  
                            DELETE  colorgrouprelation
                            WHERE   colorgroupid NOT IN ( SELECT
                                                              colorgroupid
                                                          FROM
                                                              colorgroup )
                                    AND colorgroupid <> 1  
                        END  
                    IF EXISTS ( SELECT  [name]
                                FROM    [colorgroup]
                                WHERE   [name] = @name
                                        AND sysrow <> 1 ) 
                        GOTO error100  
                    BEGIN TRAN INsertC  
                    INSERT  INTO [colorgroup]
                            ( [name], [remark], [Sysrow] )
                    VALUES  ( @name, @remark, @SysRow )   
                    SELECT  @CSgroupid = @@IDENTITY  
                    IF @@error <> 0 
                        BEGIN  
                            ROLLBACK TRAN INsertC  
                            GOTO error1 --插入颜色组主表失败  
                        END    
                    COMMIT TRAN INsertC  
      --  Select @CSgroupid=ColorGroupId From ColorGroup Where [name] =@name  
                    GOTO succee  
                END  
            IF @cMode = 'M' 
                BEGIN  
                    IF EXISTS ( SELECT  [name]
                                FROM    [colorgroup]
                                WHERE   [colorgroupid] <> @CSgroupid
                                        AND [name] = @name
                                        AND sysrow <> 1 ) 
                        GOTO error100  
                    BEGIN TRAN  
                    UPDATE  [colorgroup]
                    SET     [name] = @name ,
                            remark = @remark
                    WHERE   colorgroupid = @CSgroupid  
                    IF @@rowcount = 0 
                        BEGIN  
                            ROLLBACK TRAN   
                            GOTO error2--更新颜色组主表失败  
                        END   
   
                    COMMIT TRAN    
                    GOTO succee  
                END  
            IF @cMode = 'D' 
                BEGIN  
                    IF @CSgroupid = 1 
                        GOTO succee  
					--if  exists (select * from Ptype where ColorGroupId =@CSgroupid and deleted = 0 )
					--BEGIN
					--   if NOT Exists(SELECT * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZCS')  
					--	goto error2    
					--   else 
					--	Update Ptype Set ColorGroupId = 0 where ColorGroupId =@CSgroupid
					--END
					-- else  
						BEGIN TRAN D  
							Update Ptype Set ColorGroupId = 0 where ColorGroupId =@CSgroupid
							DELETE  FROM ColorGroupRelation
							WHERE   ColorGroupId = @CSgroupid  
							DELETE  FROM ColorGroup
							WHERE   ColorGroupId = @CSgroupid  
						COMMIT TRAN D  
                    GOTO succee  
                END  
            IF @cMode = 'DD' 
                BEGIN  
                    IF @CSgroupid = 1 
                        GOTO succee  
                    BEGIN TRAN D  
                    DELETE  FROM ColorGroupRelation
                    WHERE   ColorGroupId = @CSgroupid  
                    DELETE  FROM ColorGroup
                    WHERE   ColorGroupId = @CSgroupid  
                    COMMIT TRAN D  
                    GOTO succee  
                END  
        END  
    IF @tablename = 'SG' 
        BEGIN    
            IF @cMode = 'A' 
                BEGIN    
                    IF EXISTS ( SELECT  [name]
                                FROM    [sizegroup]
                                WHERE   [name] = @name ) 
                        GOTO error101  
                    BEGIN TRAN INSERTA  
                    EXEC [dbo].[XW_GetUpdateTag] 'SizeGroup', @UpdateTag OUTPUT
                    INSERT  INTO [sizegroup]
                            ( [name], [remark],UpdateTag )
                    VALUES  ( @name, @remark ,@UpdateTag)   
                    IF @@rowcount = 0 
                        BEGIN  
                            ROLLBACK TRAN INSERTA  
                            GOTO error3--插入尺码组主表失败  
                        END   
                    COMMIT TRAN INSERTA  
                    SELECT  @CSgroupid = SizeGroupId
                    FROM    SizeGroup
                    WHERE   [name] = @name  
                    GOTO succee  
                END  
            IF @cMode = 'M' 
             --   BEGIN  
        --if exists(Select * from pmmain where sizegroupid=@CSgroupid) return -7  
                BEGIN    
                    IF EXISTS ( SELECT  [name]
                                FROM    [sizegroup]
                                WHERE   [sizegroupid] <> @CSgroupid
                                        AND [name] = @name ) 
                        GOTO error101  
                    BEGIN TRAN  
                    EXEC [dbo].[XW_GetUpdateTag] 'SizeGroup', @UpdateTag OUTPUT
                    UPDATE  [sizegroup]
                    SET     [name] = @name ,
                            remark = @remark,
							UpdateTag=@UpdateTag
                    WHERE   [sizegroupid] = @CSgroupid  
                    IF @@rowcount = 0 
                        BEGIN  
                            ROLLBACK TRAN   
                            GOTO error4--更新尺码组主表失败  
                        END   
                    COMMIT TRAN   
                    GOTO succee  
                END  
            IF @cMode = 'D' 
                BEGIN  
                    IF @CSgroupid = 1 
                        GOTO succee  
          		   if exists (select * from Ptype where SizeGroupId =@CSgroupid and deleted = 0) goto error102  
                    BEGIN TRAN D  
                    DELETE  FROM SizeGroupRelation
                    WHERE   SizeGroupId = @CSgroupid  
                    DELETE  FROM SizeGroup
                    WHERE   SizeGroupId = @CSgroupid  
                    COMMIT TRAN D  
                    GOTO succee  
                END  
        END     
    succee:  
    RETURN 0  
    error1:  
    RETURN -1  
    error2:  
    RETURN -2  
    error3:  
    RETURN -3  
    error4:  
    RETURN -4  
    error100:  
    RETURN -5  
    error101:  
    RETURN -6  
    error102:  
    RETURN -7  

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].[FzInsertP]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FzInsertP]
GO






--  ********************************************************************************************
--  ||                                                                                        
--  ||   过程名称： FzInsertP                                   
--  ||   过程功能：添加基本信息--仓库
--  ||=========================================================================================
--  ||   参数说明：  参数名称         类型            意义                     输入输出
--  ||            -----------------------------------------------------------------------------
--  ||  	@Parid 		varchar(50),                                             --父亲ID号1
--  ||  	@dbname        	varchar(30),                                             --操作的数据库表名2
--  ||  	@FullName 	varchar(66),                                             --商品全名3
--  ||  	@Name		varchar(30),                                             --商品简名4
--  ||  	@UserCode 	varchar(26),                                             --用户编码5
--  ||  	@Standard 	varchar(20),                                             --商品规格6
--  ||  	@Type	 	varchar(20),                                             --商品类型7
--  ||  	@Area	 	varchar(30),                                             --商品产地8
--  ||  	@Unit1 		varchar(8),                                              --商品单位1  9
--  ||  	@Unit2 		varchar(8),                                              --商品单位2  10
--  ||  	@UnitRate1 	numeric(24,10),                                          --单位关系1  11
--  ||  	@UnitRate2 	numeric(24,10),                                          --单位关系2  12
--  ||  	@preprice1 	numeric(24,10),                                          --预设售价1  13
--  ||  	@preprice2 	numeric(24,10),                                          --预设售价2  14
--  ||  	@preprice3 	numeric(24,10),                                          --预设售价3  15
--  ||  	@preprice4 	numeric(24,10),                                          --预设售价4  16
--  ||	        @retailprice    numeric(24,10),		  			         --零售价
--  ||	        @minprice       numeric(24,10),					         --最低售价
--  ||  	@LifeMonth 	smallint,                                                --保质期月17
--  ||  	@LifeDay 	smallint,                                                --保质期天18
--  ||  	@CostMode	smallint,                                                --成本算法19
--  ||  	@Comment 	varchar(256),                                            --备注20
--  ||  	@namepy	        varchar(60),                                                     --全名简拼21
--  ||  	@Barcode	varchar(30),                                             --商品条码22
--  ||  	@sizegroupid    int,                                                   --尺码组23
--  ||  	@colorgroupid   int,                                                    --颜色组24
--  ||  	@breakwarn      numeric(24,10),                                         --断码报警数25
--  ||  	@Formatid       varchar(10),                                         --条码格式26
--  ||  	@cspz           int,                                                --颜色尺码配置
--  ||  	@backRec        int  output,						 --
--  ||  	@material	int,                                                  --面料
--  ||  	@season         int,                                                   --季节
--  ||  	@category       int,	                                                --品牌
--  ||  	 @year          int,		                                         --年度
--  ||               -- @SPPIC  image,		                                       -- 商品图片
--  ||  	 @trade         bit,                                              --可否换货0：不能换货，1：可以换货
--  ||  	 @stop          bit                                               -- 是否停用
--  ||         @discount        int 						         折扣0
--  ||        @discount1        int                                                      折扣1
--  ||        @discount2	int							 折扣2
--  ||        @discount3	int							 折扣3
--  ||=========================================================================================   
--  ||    返回值： 值               说明               
--  ||                   -1                  -- 数据库操作失败！
--  ||                   -2                -- 此记录已经过账，不能再分类！
--  ||                   -3                  -- 父亲ID号不存在！
--  ||                   -4                -- 系统行不允许修改！
--  ||                   -6                 有相同条码的记录存在
--  ||	            -7                插入的颜色、尺码的条码失败
--  ||=========================================================================================

/*
cqhua 2011-8-29
尺码组改变
*/
CREATE    PROCEDURE FzInsertP
    (
      @Parid VARCHAR(50) ,                                             --父亲ID号1
      @dbname VARCHAR(30) ,                                             --操作的数据库表名2
      @FullName VARCHAR(66) ,                                             --商品全名3
      @Name VARCHAR(30) ,                                             --商品简名4
      @UserCode VARCHAR(26) ,                                             --用户编码5
      @Standard VARCHAR(20) ,                                             --商品规格6
      @Type VARCHAR(20) ,                                             --商品类型7
      @Area VARCHAR(30) ,                                             --商品产地8
      @Unit1 VARCHAR(8) ,                                               --商品单位1  9
      @Unit2 VARCHAR(8) ,                                               --商品单位2  10
      @UnitRate1 NUMERIC(24, 10) = 1,                                        --单位关系1  11
      @UnitRate2 NUMERIC(24, 10) = 1,                                        --单位关系2  12
      @preprice1 NUMERIC(24, 10) ,                                        --预设售价1  13
      @preprice2 NUMERIC(24, 10) ,                                        --预设售价2  14
      @preprice3 NUMERIC(24, 10) ,                                        --预设售价3  15
      @preprice4 NUMERIC(24, 10) ,                                        --预设售价4  16
      @retailprice NUMERIC(24, 10) ,			            --零售价
      @minprice NUMERIC(24, 10) ,				--最低售价
      @LifeMonth SMALLINT ,                                                    --保质期月17
      @LifeDay SMALLINT ,                                                    --保质期天18
      @CostMode INT ,                                                           --成本算法19
      @Comment VARCHAR(256) ,                                           --备注20
      @namepy VARCHAR(100) ,                                             --全名简拼21
      @Barcode VARCHAR(30) ,                                             --商品条码22
      @sizegroupid INT ,                                                           --尺码组23
      @colorgroupid INT ,                                                           --颜色组24
      @breakwarn NUMERIC(24, 10) ,                                       --断码报警数25
      @Formatid VARCHAR(10) ,                                             --条码格式26
      @cspz INT ,                                                            --颜色尺码配置
      @backRec INT OUTPUT ,--
      @material INT ,                                                            --面料
      @season INT ,                                                           --季节
      @category INT ,                                                           --品牌
      @year INT ,                                                            --年度
               -- @SPPIC image,                                                      -- 商品图片
      @trade BIT ,                                                            --可否换货0：不能换货，1：可以换货
      @stop BIT ,                                                                     --是否停用  0：没有停用，1：已经停用
      @discount NUMERIC(24, 10) ,
      @discount1 NUMERIC(24, 10) ,
      @discount2 NUMERIC(24, 10) ,
      @discount3 NUMERIC(24, 10) ,
      @newtypeid VARCHAR(50) OUTPUT ,
      @StopDate VARCHAR(10) = '' ,
      @ColorIdList VARCHAR(1000) = '' ,
      @SizeIdList VARCHAR(1000) = '' ,
      @iPa1 INT ,
      @iPa2 INT ,
      @iPa3 INT ,
      @iPa4 INT ,
      @Issuedate VARCHAR(10) = '' ,
      @btypeid VARCHAR(50) = '' ,
      @changerule INT ,
      @Custom1 VARCHAR(255) = '' ,
      @Custom2 VARCHAR(255) = '' ,
      @Custom3 VARCHAR(255) = '' ,
      @Custom4 VARCHAR(255) = '' ,
      @Custom5 VARCHAR(255) = '' ,
      @singleunit INT = 0,
      @BuyUnit INT = 1,
      @SaleUnit INT = 1,
      @PhUnit INT =1,
      @GoodsUnit INT = 1,
      @AttributeId1 INT = 0,                      --与辅助属性类型对应
	  @AttributeId2 INT = 0,
      @AttributeId3 INT = 0,
	  @AttributeId4 INT = 0,
	  @AttributeId5 INT = 0,
	  @AttributeId6 INT = 0,
	  @AttributeId7 INT = 0,
	  @AttributeId8 INT = 0
    )
AS 
    DECLARE @nReturntype INT
    DECLARE @EtypeId_1 VARCHAR(50)
    DECLARE @nSoncount INT
    DECLARE @nSonnum INT
    DECLARE @leveal SMALLINT
    DECLARE @ParRec INT
    DECLARE @BarConID INT
    DECLARE @Stats1 INT
    DECLARE @Stats2 INT
    DECLARE @UpdateTag INT
-- 取得ID号
    EXEC @nReturntype= FzcreateId @ParId, @dbname, @EtypeId_1 OUT,
        @nSonnum OUT, @nSoncount OUT, @ParRec OUT
    IF @nReturntype = -101 
        GOTO error111 --parid不存在
    IF @nReturntype = -102 
        GOTO error112--有相关数据存在
    IF @nReturntype = -108 
        GOTO error108--有相关数据存在
    IF @nReturntype = -109 
        GOTO error109--有相关数据存在
    IF @nReturntype = -126 
        GOTO error126--有相关数据存在
    IF @nReturntype = -103 
        GOTO error113--未取得儿子编码
    IF @nReturntype = -133 
        GOTO error133--未取得儿子编码
    IF @nReturntype = -138 
        GOTO error138--未取得儿子编码
    IF @nReturntype = -150 
        GOTO error150--未取得儿子编码
    IF @nReturntype = -153 
    	GOTO error153--未取得儿子编码
    IF @nReturntype = -155
    	GOTO error155--未取得儿子编码
    IF @nReturntype = -156
	GOTO error156--未取得儿子编码
    IF @nReturntype = -157
	GOTO error157--未取得儿子编码  商品已经停用
    IF @nReturntype = -158
	GOTO error158--未取得儿子编码  商品已经停用


    IF @Issuedate = '' 
        SET @Issuedate = CONVERT(CHAR(10), GETDATE(), 121)
        
    IF @Parid <> ''    --分类新增的情况下清除父类商品的辅助单位
     BEGIN
      	UPDATE dbo.Ptype SET Unit2 = '' WHERE TypeID = @Parid AND Unit2 <> ''
     END    
        
-- 查找编号和全名不能完全相同
--读取系统配置表中的编号、全名配置规则
    SELECT  @Stats1 = stats
    FROM    syscon
    WHERE   [order] = 81
    SELECT  @Stats2 = stats
    FROM    syscon
    WHERE   [order] = 82
    IF @Stats1 = 1 
        IF EXISTS ( SELECT  [typeid]
                    FROM    ptype
                    WHERE   [typeId] = @EtypeId_1
                            OR ( fullname = @fullname
                                 AND [deleted] <> 1
                               ) ) 
            GOTO error114
    IF @Stats2 = 1 
        IF EXISTS ( SELECT  [typeid]
                    FROM    ptype
                    WHERE   [typeId] = @EtypeId_1
                            OR ( usercode = @usercode
                                 AND [deleted] <> 1
                               ) ) 
            GOTO error115
    IF @Stats1 = 0
        AND @Stats2 = 0 
        IF EXISTS ( SELECT  [typeid]
                    FROM    ptype
                    WHERE   [typeId] = @EtypeId_1
                            OR ( fullname = @fullname
                                 AND usercode = @usercode
                                 AND [deleted] <> 1
                               ) ) 
            GOTO error117
--条码相同
    IF ( LEN(RTRIM(LTRIM(@Barcode))) > 0 ) 
        BEGIN  
            IF EXISTS ( SELECT  [typeid]
                        FROM    ptype
                        WHERE   [typeId] = @EtypeId_1
                                OR ( Barcode = @Barcode )
                                AND [deleted] <> 1 ) 
                GOTO error200
        END
    IF EXISTS ( SELECT  getid
                FROM    dbo.GetIdListTable(@ColorIdList)
                WHERE   getid NOT IN ( SELECT   colorid
                                       FROM     color ) ) 
        GOTO error1117
    IF EXISTS ( SELECT  getid
                FROM    dbo.GetIdListTable(@SizeIdList)
                WHERE   getid NOT IN ( SELECT   sizeid
                                       FROM     size ) ) 
        GOTO error1118

--向表中写入数据
    BEGIN TRAN InsertP
    SELECT  @leveal = [leveal]
    FROM    ptype
    WHERE   [Typeid] = @Parid
    SELECT  @leveal = @leveal + 1

    EXEC [dbo].[XW_GetUpdateTag] 'Ptype', @UpdateTag OUTPUT

	IF @SizeIdList ='1'
		SET @sizegroupid =1
    INSERT  INTO [ptype]
            ( [typeId] ,
              [Parid] ,
              [leveal] ,
              [soncount] ,
              [sonnum] ,
              [FullName] ,
              [Name] ,
              [UserCode] ,
              [Standard] ,
              [Type] ,
              [Area] ,
              [Unit1] ,
              [Unit2] ,
              [UnitRate1] ,
              [UnitRate2] ,
              retailprice ,
              [costmode] ,
              [Comment] ,
              [namepy] ,
              [Barcode] ,
              breakwarn ,
              formatid ,
              cspz ,
              trade ,
              stop ,
              StopDate ,
              issueDate ,
              ColorIdList ,
              SizeIdList ,
              updateTag ,
              btypeid1 ,
              changerule ,
              PCustom1 ,
              PCustom2 ,
              PCustom3 ,
              PCustom4 ,
              PCustom5,
			  sizegroupid,
			  singleunit,
              BuyUnit,
              SaleUnit,
              PhUnit,
              GoodsUnit,
              MininumPrice
            )
    VALUES  ( @EtypeId_1 ,
              @Parid ,
              @leveal ,
              0 ,
              0 ,
              @FullName ,
              @Name ,
              @UserCode ,
              @Standard ,
              @Type ,
              @Area ,
              @Unit1 ,
              @Unit2 ,
              @UnitRate1 ,
              @UnitRate2 ,
              @retailprice ,
              @CostMode ,
              @Comment ,
              @namepy ,
              @Barcode ,
              @breakwarn ,
              @formatid ,
              @cspz ,
              @trade ,
              @stop ,
              @StopDate ,
              @Issuedate ,
              @ColorIdList ,
              @SizeIdList ,
              @UpdateTag ,
              @btypeid ,
              @changerule ,
              @Custom1 ,
              @Custom2 ,
              @Custom3 ,
              @Custom4 ,
              @Custom5,
			  @sizegroupid,
		      @singleunit,
              @BuyUnit,
              @SaleUnit,
              @PhUnit,
              @GoodsUnit,
              @minprice
            )
    IF @@rowcount = 0 --写数据失败回滚事务
        BEGIN
            ROLLBACK TRAN InsertP 
            RETURN -1
        END 
    ELSE --写数据成功则更新儿子计数（现有、和曾有的儿子数）
        BEGIN
            DELETE  ptypeColor
            WHERE   ptypeid = @EtypeId_1
                  
            IF @@error <> 0 --写数据失败回滚事务
                BEGIN
                    ROLLBACK TRAN InsertP 
                    RETURN -1
                END  
            INSERT  INTO PtypeColor
                    ( Ptypeid ,
                      Colorid
                    )
                    SELECT  @EtypeId_1 ,
                            getid
                    FROM    dbo.GetIdListTable(@ColorIdList)
            IF @@error <> 0 --写数据失败回滚事务
                BEGIN
                    ROLLBACK TRAN InsertP 
                    RETURN -1
                END  

            DELETE  ptypeSize
            WHERE   ptypeid = @EtypeId_1
                  
            IF @@error <> 0 --写数据失败回滚事务
                BEGIN
                    ROLLBACK TRAN InsertP 
                    RETURN -1
                END  
            INSERT  INTO ptypeSize
                    ( Ptypeid ,
                      Sizeid
                    )
                    SELECT  @EtypeId_1 ,
                            getid
                    FROM    dbo.GetIdListTable(@SizeIdList)
            IF @@error <> 0 --写数据失败回滚事务
                BEGIN
                    ROLLBACK TRAN InsertP 
                    RETURN -1
                END                       
             
            UPDATE  [ptype]
            SET     [sonnum] = @nSonnum + 1 ,
                    [soncount] = @nSoncount + 1 ,
                    UpdateTag = @UpdateTag
            WHERE   [typeid] = @Parid
            SELECT  @backRec = @@identity 
        END
    IF EXISTS ( SELECT  Ptypeid
                FROM    Ptypebar
                WHERE   Ptypeid = @Parid ) 
        DELETE  ptypebar
        WHERE   Ptypeid = @Parid
    IF ( LEN(@Barcode) > 0 ) 
        BEGIN  
			EXEC GeneratePtypeBar @Formatid,@EtypeId_1,@cspz,@Barcode,@ColorIdList,@SizeIdList,@AttributeId1,@AttributeId2,@AttributeId3,@AttributeId4,@AttributeId5,@AttributeId6,@AttributeId7,@AttributeId8,@Btypeid
        END

--设置系统数据表中的条码格式     
    IF @formatid = '1' 
        SELECT  @BarConID = 1
    ELSE 
        IF @formatid = '2' 
            SELECT  @BarConID = 0
        ELSE 
            SELECT  @BarConID = 2
    UPDATE  sysdata
    SET     subvalue = @BarConID
    WHERE   subno = 25

	delete from PriceModifyHis where PtypeId = @Parid --删除父类商品价格修改记录

	--商品颜色不包含在已有的颜色组中，新增颜色组
	--IF NOT EXISTS(SELECT * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZCS') AND NOT EXISTS (select * FROM  (select distinct replace(','+dbo.GetColoridlist(colorgroupid)+',',',,',',') as colorIdlistOrder from colorGroupRelation) X WHERE dbo.SizeListInclude(colorIdlistOrder,@colorIdlist)=1 )
	--BEGIN
	--	INSERT INTO colorGroup(name,remark,sysrow,[order])  select (select '系统颜色组'+(select Convert(varchar(10),isnull(max(colorGroupid),1)) from colorGroup)) as name,'系统升级自动生成',0,10000
	--	INSERT INTO colorGroupRelation(colorGroupID,colorid,rec,[order]) select @@identity,getid,0,iorder from  GetIdListTable(@colorIdlist)
	--END

	--UPDATE Ptype SET ColorGroupID = 1 WHERE   typeid=@EtypeId_1 AND ColorGroupID=0 AND @colorIdlist ='1'
	
	--UPDATE Ptype SET ColorGroupID = S.Colorgroupid
	--FROM Ptype p INNER JOIN  (select distinct Colorgroupid,replace(','+dbo.GetColoridlist(Colorgroupid)+',',',,',',') as colorIdlistOrder from ColorGroupRelation) S 
	--ON dbo.SizeListInclude(S.ColorIdlistOrder,Coloridlist)=1 
	--WHERE P.typeid=@EtypeId_1 AND P.ColorGroupID=0


      
--以上操作完全通过则提交事务
    COMMIT TRAN InsertP
    GOTO succee
    succee:
    SELECT  @newtypeid = @EtypeId_1
    RETURN  0--增加记录成功


    error108:
    RETURN -108 --盘点使用过

    error109:
    RETURN -109 --订单使用过
    error126:
    RETURN -126 --商品对照码存在，不能分类
    error111:
      
    RETURN -1--输入的父亲ID 号不存在
    error112:
   
    RETURN -2--有相关数据存在
    error113:
     
    RETURN -3--未取的儿子编码
    error114:
 
    RETURN -4--有相同的全名存在
    error200:
   
    RETURN -6--有相同条码的数据存在
    error115:
    RETURN -5--有相同的编码存在
    error117:
    RETURN -7--有相同编码和全名的数据存在

    error1117:
    RETURN -17--颜色不存存在
    error1118:
    RETURN -18--尺码不存存在

    error133:
    RETURN -133--促销使用过
    error138:
    RETURN -138--物价管理使用过，不能分类
    error150:
    RETURN -150--POS小票使用过，不能分类
    
	error153:
	return -153--智能配货使用过，不能分类

	error155:
	RETURN -155  --VIP设置使用过，不能分类
	error156:
	RETURN -156  --退换货调整单使用过，不能分类
	error157:
	RETURN -157  --商品已经停用，不能分类
	error158:
	RETURN -158  --智能配货使用过，不能分类
    
    errorcur:
    BEGIN
        CLOSE cur_color 
        DEALLOCATE cur_color 
        CLOSE cur_size 
        DEALLOCATE cur_size
        ROLLBACK TRAN InsertP 
        RETURN -7      
    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].[FZInsertColorSize_mop]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
  DROP PROCEDURE [dbo].[FZInsertColorSize_mop]
GO




/*写入商品颜色或尺码的基本信息  
       0     执行成功  
       －1 执行失败  
       －2  有相同名称的颜色、尺码存在  
    - 3  有相同编码的颜色、尺码存在  
*/  
CREATE  PROCEDURE FZInsertColorSize_mop
  (
    @tablename VARCHAR(1) ,         --输入的表名'C:颜色表，S：为尺码表'  
    @name VARCHAR(30) ,        --设置颜色名称  
    @barcode VARCHAR(230) ,        --相应条码  
    @remark VARCHAR(100) ,       --用户说明  
    @iMode VARCHAR(1) ,         --操作方式  增加A、修改M、删除D
    @csid INT                 --旧的颜色、尺码   
    
  )
AS 
/*
alter by hww 2011年8月17日15:14:04
在删除尺码时，增加对配码包的检查，如果被配码包占用，则不能删除
*/
  DECLARE @colorgroupid INT ,
    @sizegroupid VARCHAR(30) ,
    @oldbar VARCHAR(30)  
  DECLARE @oldBcon VARCHAR(30) ,
    @ptypeid VARCHAR(50) ,
    @formatid VARCHAR(10) ,
    @oobarcode VARCHAR(30)   
  DECLARE @oldCGid INT ,
    @oldSGid INT ,
    @cid INT    
  DECLARE @colorid INT ,
    @cbar VARCHAR(10) ,
    @sieeid INT ,
    @sbar VARCHAR(10) ,
    @bar VARCHAR(50)   
  DECLARE @Stats1 INT  
  DECLARE @Stats2 INT  
  SELECT  @Stats1 = stats
  FROM    syscon
  WHERE   [order] = 81  
  SELECT  @Stats2 = stats
  FROM    syscon
  WHERE   [order] = 82  
  DECLARE @UpdateTag INT
  IF @tablename = 'C' 
    BEGIN  

      IF @iMode = 'A' 
        BEGIN  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   [name] = @name
                              AND @Stats1 = 1 ) 
            GOTO error100 --不允许名称相同  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   [barcode] = @barcode
                              AND @Stats2 = 1 ) 
            GOTO error101--不允许编码相同  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [name] = @name
                              AND barcode = @barcode
                              AND @barcode <> '' ) 
            GOTO error100  
                
          EXEC [dbo].[XW_GetUpdateTag] 'Color', @UpdateTag OUTPUT
          INSERT  INTO [color] ( [name], barcode, [remark], updateTag )
          VALUES  ( @name, @barcode, @remark, @UpdateTag )   
          IF @@rowcount = 0
            OR @@Error <> 0 
            BEGIN  
              GOTO error111  
            END   
           --if exists(select [barcode]  from [color]  where colorid <>@csid and [name]=@name and barcode<>@barcode and @barcode <> '')   
           --   goto error106   
          GOTO succee  
        END   
       /*修改颜色*/  
      IF @iMode = 'M' 
        BEGIN  
          IF NOT EXISTS(SELECT 1 FROM dbo.[color] WHERE ColorID = @csid) --判断要操作的信息是否存在
            GOTO error107 
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [name] = @name
                              AND @Stats1 = 1 )--不允许名称相同  
            GOTO error100  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [barcode] = @barcode
                              AND @Stats2 = 1 )  --不允许编码相同  
            GOTO error101  
                   
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [name] = @name
                              AND barcode = @barcode
                              AND @barcode <> '' ) 
            GOTO error100  
          SELECT  colorgroupID
          INTO    #tmptable
          FROM    colorgroup
          WHERE   colorgroupID IN ( SELECT  colorgroupid
                                    FROM    colorgrouprelation
                                    WHERE   colorid = @csid )
                  AND colorgroupid IN ( SELECT  colorgroupid
                                        FROM    colorgrouprelation
                                        WHERE   colorid IN ( SELECT colorid
                                                             FROM   color
                                                             WHERE  ( [name] = @name
                                                                      OR ( barcode = @barcode
                                                                           AND @barcode <> ''
                                                                         )
                                                                    )
                                                                    AND colorid <> @csid ) )  
          IF EXISTS ( SELECT  *
                      FROM    #tmptable ) 
            BEGIN  
              DROP TABLE #tmptable         
              GOTO error103  
            END  
          DROP TABLE #tmptable      
     
          SELECT  @oldbar = barcode
          FROM    [color]
          WHERE   colorid = @csid  
          EXEC [dbo].[XW_GetUpdateTag] 'Color', @UpdateTag OUTPUT
          UPDATE  [color]
          SET     [name] = @name, barcode = @barcode, [remark] = @remark, updateTag = @UpdateTag
          WHERE   colorid = @csid  
          IF @@rowcount = 0 
            BEGIN   
              GOTO error111  
            END  
          IF @oldbar + '1' <> @barcode + '1' --加一个常量字符串，区分是否有尾部空格  
            BEGIN  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + @barcode + ( SELECT BarCode FROM [Size] c WHERE c.SizeId = a.SizeId )
                                           WHEN cspz = 1 THEN b.barcode + @barcode
                                           WHEN cspz = 2 THEN b.barcode + ( SELECT MAX (BarCode) FROM [Size] c WHERE c.SizeId = a.SizeId )
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   colorid = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '1'  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + ( SELECT BarCode FROM [Size] c WHERE c.SizeId = a.SizeId ) + @barcode
                                           WHEN cspz = 1 THEN b.barcode + @barcode
                                           WHEN cspz = 2 THEN b.barcode + ( SELECT MAX (BarCode) FROM [Size] c WHERE c.SizeId = a.SizeId )
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   colorid = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '2'  
            END   
      		    --系统条码修改后，如果存在唯一码，要删除 ptypeuniquecode
          IF @oldbar <> @barcode 
            BEGIN
              DELETE  FROM ptypeuniquecode
              WHERE   ColorID = @csid 
              DELETE  FROM PtypeUniqueCheck
              WHERE   ColorID = @csid 
            END
          GOTO succee  
        END  
      IF @iMode = 'D' 
        BEGIN  
          IF @csid = '1' 
            GOTO succee  
          IF EXISTS ( SELECT  *
                      FROM    ptypecolor
                      WHERE   colorid = @csid ) 
            GOTO error100  

          IF EXISTS ( SELECT  *
                      FROM    ColorGroupRelation
                      WHERE   colorid = @csid ) 
            GOTO error100  
            ELSE IF EXISTS(SELECT 1 FROM dbo.AutoPhGrdData WHERE PCTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF EXISTS(SELECT 1 FROM dbo.AutoPhOrderGrdData WHERE PCTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF NOT EXISTS(SELECT 1 FROM dbo.[color] WHERE ColorID = @csid) --判断要删除的信息是否不存在
            GOTO error107 
            
          ELSE 
            BEGIN  
              DELETE  FROM [color]
              WHERE   colorid = @csid  
              IF @@error <> 0 
                BEGIN  
                  GOTO error111  
                END  
              DELETE  FROM COLORGROUPRELATION
              WHERE   colorid = @csid  
              IF @@error <> 0 
                BEGIN  
                  GOTO error111  
                END  
              GOTO succee  
            END  
        END  
    END  
  IF @tablename = 'S' 
    BEGIN  
      IF @iMode = 'A' 
        BEGIN    
          IF EXISTS ( SELECT  [name]
                      FROM    [size]
                      WHERE   [name] = @name
                              AND @Stats1 = 1 ) 
            GOTO error100 --不允许名称相同  
          IF EXISTS ( SELECT  [name]
                      FROM    [size]
                      WHERE   [barcode] = @barcode
                              AND @Stats2 = 1 ) 
            GOTO error101--不允许编码相同  
          IF EXISTS ( SELECT  *
                      FROM    [size]
                      WHERE   [name] = @name
                              AND barcode = @barcode
                              AND @barcode <> '' ) 
            GOTO error100  
        
          EXEC [dbo].[XW_GetUpdateTag] 'Size', @UpdateTag OUTPUT
          INSERT  INTO [size] ( [name], barcode, remark, updateTag )
          VALUES  ( @name, @barcode, @remark, @UpdateTag )   
          IF @@rowcount = 0 
            BEGIN  
              GOTO error111  
            END   
                     --if exists(Select * from [size] where [name]=@name and barcode <> @barcode and @barcode <> '')    
                      --  goto error106  
          GOTO succee  
        END  
    
      IF @iMode = 'M' 
        BEGIN  
          IF NOT EXISTS(SELECT 1 FROM dbo.[SIZE] WHERE SizeID = @csid) --判断要操作的信息是否存在
            GOTO error107 
          IF EXISTS ( SELECT  1
                      FROM    [size]
                      WHERE   sizeid <> @csid
                              AND [name] = @name
                              AND @Stats1 = 1 )--不允许名称相同  
            GOTO error100  
          IF EXISTS ( SELECT  1
                      FROM    [size]
                      WHERE   sizeid <> @csid
                              AND [barcode] = @barcode
                              AND @Stats2 = 1 )  --不允许编码相同  
            GOTO error101  
          IF EXISTS ( SELECT  *
                      FROM    [size]
                      WHERE   [name] = @name
                              AND BarCode = @barcode
                              AND sizeid <> @csid
                              AND @barcode <> '' ) 
            GOTO error100  
      
          SELECT  sizegroupID
          INTO    #tmptables
          FROM    sizegroup
          WHERE   sizegroupID IN ( SELECT sizegroupID
                                   FROM   Sizegrouprelation
                                   WHERE  sizeid = @csid )
                  AND sizegroupID IN ( SELECT sizegroupID
                                       FROM   Sizegrouprelation
                                       WHERE  sizeid IN ( SELECT  sizeid
                                                          FROM    size
                                                          WHERE   ( [name] = @name
                                                                    OR ( barcode = @barcode
                                                                         AND @barcode <> ''
                                                                       )
                                                                  )
                                                                  AND sizeid <> @csid ) )  
          IF EXISTS ( SELECT  *
                      FROM    #tmptables ) 
            BEGIN  
              DROP TABLE #tmptables         
              GOTO error103  
            END  
          DROP TABLE #tmptables         
          SELECT  @oldbar = barcode
          FROM    [size]
          WHERE   sizeid = @csid  
          EXEC [dbo].[XW_GetUpdateTag] 'Size', @UpdateTag OUTPUT
          UPDATE  [size]
          SET     [name] = @name, barcode = @barcode, [remark] = @remark, updateTag = @UpdateTag
          WHERE   sizeid = @csid  
          IF @@rowcount = 0 
            BEGIN   
              GOTO error111  
            END  
          IF EXISTS ( SELECT  *
                      FROM    sizegrouprelation sg ,
                              size s
                      WHERE   s.sizeid = sg.sizeid
                              AND sg.sizeid = @csid
                              AND ( s.name = @name )
                              AND sizegroupid IN ( SELECT sg.sizegroupid
                                                   FROM   sizegrouprelation sg ,
                                                          size s
                                                   WHERE  s.sizeid = sg.sizeid
                                                          AND s.Name = @name
                                                          AND sg.sizeid <> @csid ) ) 
            BEGIN   
              GOTO error103   
            END  
   
    
          IF @oldbar <> @barcode 
            BEGIN  
--如果条码变动,则更新条码信息  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid ) + @barcode
                                           WHEN cspz = 1 THEN b.barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid )
                                           WHEN cspz = 2 THEN b.barcode + @barcode
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   SizeID = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '1'  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + @barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid )
                                           WHEN cspz = 1 THEN b.barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid )
                                           WHEN cspz = 2 THEN b.barcode + @barcode
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   SizeID = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '2'  
            END   
      		    --系统条码修改后，如果存在唯一码，要删除 ptypeuniquecode
          IF @oldbar <> @barcode 
            BEGIN
              DELETE  FROM ptypeuniquecode
              WHERE   SizeID = @csid 
              DELETE  FROM PtypeUniqueCheck
              WHERE   SizeID = @csid 
            END
          GOTO succee  
        END   
     
    
      IF @iMode = 'D' 
        BEGIN  
          IF @csid = '1' 
            GOTO succee  
          IF EXISTS ( SELECT  *
                      FROM    ptypesize
                      WHERE   sizeid = @csid ) 
            GOTO error100  
          IF EXISTS ( SELECT  *
                      FROM    SizeGroupRelation
                      WHERE   sizeid = @csid ) 
            GOTO error100  
          ELSE IF EXISTS(SELECT 1 FROM dbo.PMdetail WHERE PSTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF EXISTS(SELECT 1 FROM dbo.AutoPhGrdData WHERE PSTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF EXISTS(SELECT 1 FROM dbo.AutoPhOrderGrdData WHERE PSTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF NOT EXISTS(SELECT 1 FROM dbo.[SIZE] WHERE SizeId = @csid) --判断要删除的信息是否不存在
            GOTO error107
          ELSE           
            BEGIN                                     
              DELETE  FROM [size]
              WHERE   sizeid = @csid  
              IF @@error <> 0 
                BEGIN   
                  GOTO error111  
                END  
              DELETE  FROM SizeGROUPRELATION
              WHERE   sizeid = @csid  
              IF @@error <> 0 
                BEGIN  
                  
                  GOTO error111  
                END  
              GOTO succee  
            END  
        END  
    END   
  succee:  
               
  RETURN 0  
  error111:  
  RETURN -1  
  error100:  
  RETURN -2  
  error101:  
  RETURN -3  
  error102:  
  RETURN -4  
  error103:  
  RETURN -5 --在一个商品中存在颜色名称相同的记录  
  error106:  
  RETURN 1
 --相同颜色不同条码  
  error107:  
  RETURN -7 --删除的信息不存在



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS 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_TCGetOtypeList]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FN_TCGetOtypeList]
GO

/*---------2011年8月19日 文有明--------------------*/
/*---------增加配码包查询 @OtherType = 8-------------------*/


CREATE PROCEDURE FN_TCGetOtypeList
    (
      @seaStr VARCHAR(500),
      @OtherType INT,
      @AssistType varchar(100)  
    )
AS 
    BEGIN  
        IF @OtherType = 1  --VIP卡类型
            BEGIN
    /*	  
    select [name] as fullname,case type when 0 then '会员价卡' else '商品折扣卡'end as typename,orderid as otypeid,orderid as orec,  
       * from vipcardtypes  
    where [name] like @seaStr  
    */
                SELECT  v.[name] AS fullname,
                        CASE v.type
                          WHEN 0 THEN '会员价卡'
                          ELSE '商品折扣卡'
                        END AS typename,
                        v.orderid AS otypeid,
                        v.orderid AS orec,
                        v.*,
                        ISNULL(p.displayname, '') AS displayname
                FROM    vipcardtypes v
                        LEFT JOIN PriceType p ON v.pricetypeid = p.pricetypeid
                WHERE   v.[name] LIKE @seaStr 
            END  
        ELSE 
            IF @OtherType = 2  --尺码足
                BEGIN  
                    SELECT  [name] AS fullname,
                            sizegroupid AS otypeid,
                            sizegroupid AS orec,
                            Remark
                    FROM    sizegroup
                    WHERE   sizegroupid <> 1
                            AND [name] LIKE @seaStr  
                END  
            ELSE 
                IF @OtherType = 3  --颜色组
                    BEGIN  
                        SELECT  [name] AS fullname,
                                colorgroupid AS otypeid,
                                colorgroupid AS orec,
                                Remark
                        FROM    colorgroup
                        WHERE   colorgroupid <> 1 and not (LEFT([name],5)='系统颜色组' and remark='系统升级自动生成')
                                AND [name] LIKE @seaStr  
                    END  
                ELSE 
                    IF @OtherType = 4  --辅助属性
                        BEGIN  
                            SELECT  username AS fullname,
                                    usercode,
                                    attributeid AS otypeid,
                                    attributeid AS orec
                            FROM    assistattribute
                            WHERE   typeid = @AssistType
                                    AND username LIKE @seaStr  
                        END  
                    ELSE 
                        IF @OtherType = 5  --单据自定义字段内容
                            BEGIN  
                                SELECT  CustFieldID AS Otypeid,
                                        CustFieldValue AS FullName,
                                        CustFieldID AS oRec
                                FROM    CustomFieldDetail
                                WHERE   CustFieldID = @AssistType
                                        AND CustFieldValue LIKE @seaStr  
                            END  
                        ELSE 
                            IF @OtherType = 6  --辅助属性类型
                                BEGIN  
                                    SELECT  typename AS fullname,
                                            typeid AS otypeid,
                                            typeid AS orec
                                    FROM    assisttype
                                    WHERE   typename LIKE @seaStr  
                                END 
                            ELSE 
                                IF @OtherType = 7 --单据自定义字段类型
                                    BEGIN  
                                        IF OBJECT_ID('tempdb..#CustomField') IS NOT NULL 
                                            DROP TABLE #CustomField
                                        CREATE TABLE #CustomField
                                            (
                                              Otypeid INT,
                                              fullname VARCHAR(50),
                                              Orec [int] IDENTITY(1, 1)
                                                         NOT NULL ,
		                                )
                                        INSERT  INTO #CustomField ( OtypeId, fullname )
                                                SELECT  CustFieldID,
                                                        CustFieldName
                                                FROM    CustomField
                                                WHERE   CustFieldName LIKE @seaStr
                                                ORDER BY CustFieldID
                                        SELECT  *
                                        FROM    #CustomField
                                    END 
                                ELSE 
                                    IF @OtherType = 8 
                                        BEGIN
			                    DECLARE @sql VARCHAR(1000)
			                    Set @sql = 'SELECT  PMID AS Otypeid,UserCode,PMName AS FullName,PMID AS oRec FROM    dbo.PMmain WHERE   IsStop = 0 '
			                    Set @sql = @sql + ' and (PMName LIKE '''+@seaStr+''' or UserCode like ''' + @seaStr + ''')'
			                    
			                    IF @AssistType <> '' 
			                    SELECT @sql = @sql + ' AND PMID IN (SELECT DISTINCT PMID FROM GetPMIDTable('''+ @AssistType +'''))'
					    PRINT @sql
					    EXEC(@sql)
			                  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].[FZInsertColorSize]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
  DROP PROCEDURE [dbo].[FZInsertColorSize]
GO




/*写入商品颜色或尺码的基本信息  
       0     执行成功  
       －1 执行失败  
       －2  有相同名称的颜色、尺码存在  
    - 3  有相同编码的颜色、尺码存在  
*/  
CREATE  PROCEDURE FZInsertColorSize
  (
    @tablename VARCHAR(1) ,         --输入的表名'C:颜色表，S：为尺码表'  
    @name VARCHAR(30) ,        --设置颜色名称  
    @barcode VARCHAR(230) ,        --相应条码  
    @remark VARCHAR(100) ,       --用户说明  
    @iMode VARCHAR(1) ,         --操作方式  增加A、修改M、删除D
    @csid INT                 --旧的颜色、尺码   
    
  )
AS 
/*
alter by hww 2011年8月17日15:14:04
在删除尺码时，增加对配码包的检查，如果被配码包占用，则不能删除
*/
  DECLARE @colorgroupid INT ,
    @sizegroupid VARCHAR(30) ,
    @oldbar VARCHAR(30)  
  DECLARE @oldBcon VARCHAR(30) ,
    @ptypeid VARCHAR(50) ,
    @formatid VARCHAR(10) ,
    @oobarcode VARCHAR(30)   
  DECLARE @oldCGid INT ,
    @oldSGid INT ,
    @cid INT    
  DECLARE @colorid INT ,
    @cbar VARCHAR(10) ,
    @sieeid INT ,
    @sbar VARCHAR(10) ,
    @bar VARCHAR(50)   
  DECLARE @Stats1 INT  
  DECLARE @Stats2 INT  
  SELECT  @Stats1 = stats
  FROM    syscon
  WHERE   [order] = 81  
  SELECT  @Stats2 = stats
  FROM    syscon
  WHERE   [order] = 82  
  DECLARE @UpdateTag INT
  IF @tablename = 'C' 
    BEGIN  

      IF @iMode = 'A' 
        BEGIN  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   [name] = @name
                              AND @Stats1 = 1 ) 
            GOTO error100 --不允许名称相同  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   [barcode] = @barcode
                              AND @Stats2 = 1 ) 
            GOTO error101--不允许编码相同  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [name] = @name
                              AND barcode = @barcode
                              AND @barcode <> '' ) 
            GOTO error100  
                
          BEGIN TRAN INSERTA  
          EXEC [dbo].[XW_GetUpdateTag] 'Color', @UpdateTag OUTPUT
          INSERT  INTO [color] ( [name], barcode, [remark], updateTag )
          VALUES  ( @name, @barcode, @remark, @UpdateTag )   
          IF @@rowcount = 0
            OR @@Error <> 0 
            BEGIN  
              ROLLBACK TRAN INSERTA  
              GOTO error111  
            END   
          COMMIT TRAN INSERTA  
           --if exists(select [barcode]  from [color]  where colorid <>@csid and [name]=@name and barcode<>@barcode and @barcode <> '')   
           --   goto error106   
          GOTO succee  
        END   
       /*修改颜色*/  
      IF @iMode = 'M' 
        BEGIN  
          IF NOT EXISTS(SELECT 1 FROM dbo.[color] WHERE ColorID = @csid) --判断要操作的信息是否存在
            GOTO error107 
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [name] = @name
                              AND @Stats1 = 1 )--不允许名称相同  
            GOTO error100  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [barcode] = @barcode
                              AND @Stats2 = 1 )  --不允许编码相同  
            GOTO error101  
                   
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [name] = @name
                              AND barcode = @barcode
                              AND @barcode <> '' ) 
            GOTO error100  
          SELECT  colorgroupID
          INTO    #tmptable
          FROM    colorgroup
          WHERE   colorgroupID IN ( SELECT  colorgroupid
                                    FROM    colorgrouprelation
                                    WHERE   colorid = @csid )
                  AND colorgroupid IN ( SELECT  colorgroupid
                                        FROM    colorgrouprelation
                                        WHERE   colorid IN ( SELECT colorid
                                                             FROM   color
                                                             WHERE  ( [name] = @name
                                                                      OR ( barcode = @barcode
                                                                           AND @barcode <> ''
                                                                         )
                                                                    )
                                                                    AND colorid <> @csid ) )  
          IF EXISTS ( SELECT  *
                      FROM    #tmptable ) 
            BEGIN  
              DROP TABLE #tmptable         
              GOTO error103  
            END  
          DROP TABLE #tmptable      
     
          BEGIN TRAN   
          SELECT  @oldbar = barcode
          FROM    [color]
          WHERE   colorid = @csid  
          EXEC [dbo].[XW_GetUpdateTag] 'Color', @UpdateTag OUTPUT
          UPDATE  [color]
          SET     [name] = @name, barcode = @barcode, [remark] = @remark, updateTag = @UpdateTag
          WHERE   colorid = @csid  
          IF @@rowcount = 0 
            BEGIN  
              ROLLBACK TRAN   
              GOTO error111  
            END  
          IF @oldbar + '1' <> @barcode + '1' --加一个常量字符串，区分是否有尾部空格  
            BEGIN  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + @barcode + ( SELECT BarCode FROM [Size] c WHERE c.SizeId = a.SizeId )
                                           WHEN cspz = 1 THEN b.barcode + @barcode
                                           WHEN cspz = 2 THEN b.barcode + ( SELECT MAX (BarCode) FROM [Size] c WHERE c.SizeId = a.SizeId )
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   colorid = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '1'  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + ( SELECT BarCode FROM [Size] c WHERE c.SizeId = a.SizeId ) + @barcode
                                           WHEN cspz = 1 THEN b.barcode + @barcode
                                           WHEN cspz = 2 THEN b.barcode + ( SELECT MAX (BarCode) FROM [Size] c WHERE c.SizeId = a.SizeId )
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   colorid = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '2'  
            END   
          COMMIT TRAN  
      		    --系统条码修改后，如果存在唯一码，要删除 ptypeuniquecode
          IF @oldbar <> @barcode 
            BEGIN
              DELETE  FROM ptypeuniquecode
              WHERE   ColorID = @csid 
              DELETE  FROM PtypeUniqueCheck
              WHERE   ColorID = @csid 
            END
          GOTO succee  
        END  
      IF @iMode = 'D' 
        BEGIN  
          IF @csid = '1' 
            GOTO succee  
           
           if exists(select * from BakDly where ColorId =@csid) or
              exists(select * from DlyData where ColorId =@csid) or
              exists(select * from IniGoodsDetail where ColorId =@csid) or
              exists(select * from Goodsstockdetail where ColorId =@csid) or
              exists(select * from BakDlyOrder where ColorId =@csid) 
           GOTO error100  
          --不判断此处了，可以直接删除
          --IF EXISTS ( SELECT  *
          --            FROM    ptypecolor
          --            WHERE   colorid = @csid ) 
          --  GOTO error100  

          --IF EXISTS ( SELECT  *
          --            FROM    ColorGroupRelation
          --            WHERE   colorid = @csid ) 
          --  GOTO error100  
          --  ELSE 
          IF EXISTS(SELECT 1 FROM dbo.AutoPhGrdData WHERE PCTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF EXISTS(SELECT 1 FROM dbo.AutoPhOrderGrdData WHERE PCTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF NOT EXISTS(SELECT 1 FROM dbo.[color] WHERE ColorID = @csid) --判断要删除的信息是否不存在
            GOTO error107 
            
          ELSE 
            BEGIN  
              BEGIN TRAN D  
              DELETE  FROM [color]
              WHERE   colorid = @csid  
              IF @@error <> 0 
                BEGIN  
                  ROLLBACK TRAN D  
                  GOTO error111  
                END  
            delete from ColorGroupRelation where ColorId =@csid 
			delete from ColorGroup where not exists(select * from ColorGroupRelation where ColorId=@csid and ColorGroupID=ColorGroup.ColorGroupID)
			--商品颜色处替换,没有颜色了，替换成均色
          	update PType set ColorIdList='1',ColorGroupid=1,CSPZ =case when SizeGroupid=1 then 3 else 2 end
			where REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',',') in (',',',,') and 
			exists(select * from PtypeColor  where ColorId=@csid and PtypeId=ptype.TypeID)


			update PType set ColorIdList=
				case when left(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),1)=',' 
				then 
					case when RIGHT(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),1)=',' 
						then SUBSTRING(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),2,len(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','))-2)
					else
						RIGHT(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),len(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','))-1)			
					end
				else
					case when RIGHT(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),1)=',' 
						then SUBSTRING(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),0,len(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',',')))
					else 
						REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',',')
					end
				end
			where REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',',') not in (',',',,') and 
			exists(select * from PtypeColor  where ColorId=@csid and PtypeId=ptype.TypeID)         
			select PtypeId into #ptypeColor from ptypecolor where ColorId =@csid 
			delete from ptypecolor where ColorId =@csid
			delete from PtypeBar where ColorId =@csid  --条码表
			delete from MultiBarList where ColorId =@csid   --对照码表
			
			declare @FormatidT int,@typeId varchar(50),@cspz int,@BarcodeT VARCHAR(30),@ColorIdList VARCHAR(1000),@SizeIdList VARCHAR(1000),@AttributeId1 INT,@AttributeId2 INT,@AttributeId3 INT,@AttributeId4 INT,@AttributeId5 INT,@AttributeId6 INT,@AttributeId7 INT,@AttributeId8 INT,@Btypeid varchar(50)   
			SET @Btypeid =''
			--插入均色
			insert into PtypeColor(PtypeId,ColorId) select PtypeId,1 from #ptypeColor where  ptypeid not IN (select PtypeId from ptypecolor) 
			if exists(select * from #ptypeColor where  ptypeid not IN (select PtypeId from ptypecolor))			
			BEGIN
				declare abc cursor for select formatid,typeid,cspz,barcode,coloridlist,sizeidlist,btypeid1 from ptype p 
				inner join #ptypeColor b on p.typeid=b.ptypeid  where b.ptypeid not IN (select PtypeId from ptypecolor)
				open abc
				fetch next from abc into @FormatidT,@typeId,@cspz,@BarcodeT,@ColorIdList,@SizeIdList,@btypeid
				while @@FETCH_STATUS =0
				BEGIN
					SET @AttributeId1=0
					SET @AttributeId2=0
					SET @AttributeId3=0
					SET @AttributeId4=0
					SET @AttributeId5=0
					SET @AttributeId6=0
					SET @AttributeId7=0
					SET @AttributeId8=0
					select @AttributeId1=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =1
					select @AttributeId2=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =2
					select @AttributeId3=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =3
					select @AttributeId4=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =4
					select @AttributeId5=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =5
					select @AttributeId6=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =6
					select @AttributeId7=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =7
					select @AttributeId8=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =8
					EXEC GeneratePtypeBar @FormatidT,@typeId,@cspz,@BarcodeT,@ColorIdList,@SizeIdList,@AttributeId1,@AttributeId2,@AttributeId3,@AttributeId4,@AttributeId5,@AttributeId6,@AttributeId7,@AttributeId8,@Btypeid    
					fetch next from abc into @FormatidT,@typeId,@cspz,@BarcodeT,@ColorIdList,@SizeIdList,@btypeid
				END
				CLOSE ABC
				deallocate ABC
			END
			DROP TABLE #ptypeColor

              IF @@error <> 0 
                BEGIN  
                  ROLLBACK TRAN D  
                  GOTO error111  
                END  
              COMMIT TRAN D  
              GOTO succee  
            END  
        END  
    END  
  IF @tablename = 'S' 
    BEGIN  
      IF @iMode = 'A' 
        BEGIN    
          IF EXISTS ( SELECT  [name]
                      FROM    [size]
                      WHERE   [name] = @name
                              AND @Stats1 = 1 ) 
            GOTO error100 --不允许名称相同  
          IF EXISTS ( SELECT  [name]
                      FROM    [size]
                      WHERE   [barcode] = @barcode
                              AND @Stats2 = 1 ) 
            GOTO error101--不允许编码相同  
          IF EXISTS ( SELECT  *
                      FROM    [size]
                      WHERE   [name] = @name
                              AND barcode = @barcode
                              AND @barcode <> '' ) 
            GOTO error100  
        
          BEGIN TRAN INSERTA  
          EXEC [dbo].[XW_GetUpdateTag] 'Size', @UpdateTag OUTPUT
          INSERT  INTO [size] ( [name], barcode, remark, updateTag )
          VALUES  ( @name, @barcode, @remark, @UpdateTag )   
          IF @@rowcount = 0 
            BEGIN  
              ROLLBACK TRAN INSERTA  
              GOTO error111  
            END   
          COMMIT TRAN INSERTA  
                     --if exists(Select * from [size] where [name]=@name and barcode <> @barcode and @barcode <> '')    
                      --  goto error106  
          GOTO succee  
        END  
    
      IF @iMode = 'M' 
        BEGIN  
          IF NOT EXISTS(SELECT 1 FROM dbo.[SIZE] WHERE SizeID = @csid) --判断要操作的信息是否存在
            GOTO error107 
          IF EXISTS ( SELECT  1
                      FROM    [size]
                      WHERE   sizeid <> @csid
                              AND [name] = @name
                              AND @Stats1 = 1 )--不允许名称相同  
            GOTO error100  
          IF EXISTS ( SELECT  1
                      FROM    [size]
                      WHERE   sizeid <> @csid
                              AND [barcode] = @barcode
                              AND @Stats2 = 1 )  --不允许编码相同  
            GOTO error101  
          IF EXISTS ( SELECT  *
                      FROM    [size]
                      WHERE   [name] = @name
                              AND BarCode = @barcode
                              AND sizeid <> @csid
                              AND @barcode <> '' ) 
            GOTO error100  
      
          SELECT  sizegroupID
          INTO    #tmptables
          FROM    sizegroup
          WHERE   sizegroupID IN ( SELECT sizegroupID
                                   FROM   Sizegrouprelation
                                   WHERE  sizeid = @csid )
                  AND sizegroupID IN ( SELECT sizegroupID
                                       FROM   Sizegrouprelation
                                       WHERE  sizeid IN ( SELECT  sizeid
                                                          FROM    size
                                                          WHERE   ( [name] = @name
                                                                    OR ( barcode = @barcode
                                                                         AND @barcode <> ''
                                                                       )
                                                                  )
                                                                  AND sizeid <> @csid ) )  
          IF EXISTS ( SELECT  *
                      FROM    #tmptables ) 
            BEGIN  
              DROP TABLE #tmptables         
              GOTO error103  
            END  
          DROP TABLE #tmptables         
          BEGIN TRAN   
          SELECT  @oldbar = barcode
          FROM    [size]
          WHERE   sizeid = @csid  
          EXEC [dbo].[XW_GetUpdateTag] 'Size', @UpdateTag OUTPUT
          UPDATE  [size]
          SET     [name] = @name, barcode = @barcode, [remark] = @remark, updateTag = @UpdateTag
          WHERE   sizeid = @csid  
          IF @@rowcount = 0 
            BEGIN  
              ROLLBACK TRAN   
              GOTO error111  
            END  
          IF EXISTS ( SELECT  *
                      FROM    sizegrouprelation sg ,
                              size s
                      WHERE   s.sizeid = sg.sizeid
                              AND sg.sizeid = @csid
                              AND ( s.name = @name )
                              AND sizegroupid IN ( SELECT sg.sizegroupid
                                                   FROM   sizegrouprelation sg ,
                                                          size s
                                                   WHERE  s.sizeid = sg.sizeid
                                                          AND s.Name = @name
                                                          AND sg.sizeid <> @csid ) ) 
            BEGIN  
              ROLLBACK TRAN   
              GOTO error103   
            END  
   
    
          IF @oldbar <> @barcode 
            BEGIN  
--如果条码变动,则更新条码信息  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid ) + @barcode
                                           WHEN cspz = 1 THEN b.barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid )
                                           WHEN cspz = 2 THEN b.barcode + @barcode
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   SizeID = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '1'  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + @barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid )
                                           WHEN cspz = 1 THEN b.barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid )
                                           WHEN cspz = 2 THEN b.barcode + @barcode
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   SizeID = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '2'  
            END  
          COMMIT TRAN  
                    
      		    --系统条码修改后，如果存在唯一码，要删除 ptypeuniquecode
          IF @oldbar <> @barcode 
            BEGIN
              DELETE  FROM ptypeuniquecode
              WHERE   SizeID = @csid 
              DELETE  FROM PtypeUniqueCheck
              WHERE   SizeID = @csid 
            END
          GOTO succee  
        END   
     
    
      IF @iMode = 'D' 
        BEGIN  
          IF @csid = '1' 
            GOTO succee  
          IF EXISTS ( SELECT  *
                      FROM    ptypesize
                      WHERE   sizeid = @csid ) 
            GOTO error100  
          IF EXISTS ( SELECT  *
                      FROM    SizeGroupRelation
                      WHERE   sizeid = @csid ) 
            GOTO error100  
          ELSE IF EXISTS(SELECT 1 FROM dbo.PMdetail WHERE PSTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF EXISTS(SELECT 1 FROM dbo.AutoPhGrdData WHERE PSTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF EXISTS(SELECT 1 FROM dbo.AutoPhOrderGrdData WHERE PSTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF NOT EXISTS(SELECT 1 FROM dbo.[SIZE] WHERE SizeId = @csid) --判断要删除的信息是否不存在
            GOTO error107
          ELSE           
            BEGIN  
                                                          
              BEGIN TRAN D  
              DELETE  FROM [size]
              WHERE   sizeid = @csid  
              IF @@error <> 0 
                BEGIN  
                  ROLLBACK TRAN D  
                  GOTO error111  
                END  
              DELETE  FROM SizeGROUPRELATION
              WHERE   sizeid = @csid  
              IF @@error <> 0 
                BEGIN  
                  ROLLBACK TRAN D  
                  GOTO error111  
                END  
              COMMIT TRAN D  
              GOTO succee  
            END  
        END  
    END   
  succee:  
               
  RETURN 0  
  error111:  
  RETURN -1  
  error100:  
  RETURN -2  
  error101:  
  RETURN -3  
  error102:  
  RETURN -4  
  error103:  
  RETURN -5 --在一个商品中存在颜色名称相同的记录  
  error106:  
  RETURN 1
 --相同颜色不同条码  
  error107:  
  RETURN -7 --删除的信息不存在



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

 ---订货会相关
 SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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

-- ========================================================
-- 功能说明：		创建常用菜单项 ( 同时匹配软件狗版本号 )
-- ========================================================
CREATE PROCEDURE CreateMenuItemForShortcutMenu
(
	@chvOperator	VARCHAR(100),	-- 操作员 ID 值
	@ParentID	varchar(10),		-- 父节点 ID 值 传入的值为：%时，可查出整个菜单树记录
	@intValue		INT				-- 软件狗 DLL 通过 ASP 控件返回的加密字串
)
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)


	-- ********	判断软件狗版本号 - END	********

DECLARE @usepos char(1)
SET @usepos='0'
select @usepos=subvalue from sysdata where subname='usepos'

	IF @chvOperator<>'00000'
		IF NOT EXISTS(
		SELECT	1
		FROM	LoginUser
		WHERE	ETypeID = @chvOperator
	)
		RETURN 1	-- 操作员不存在

declare @PtypeUniqueSet varchar(10) --唯一码菜单
SET @PtypeUniqueSet='051008'
IF EXISTS(select * from sysdata where subname='PtypeUniqueSet' and subvalue>=1)
	SET @PtypeUniqueSet=''



declare @ifjm int
SET @ifjm=0
if exists(select  * from employee WHERE typeid=@chvOperator and left(branchid,5)='00004') --是否加盟操作员
BEGIN
	SET @ifjm=1
END
IF @chvOperator='00000'
select 
	Distinct 
	m.moduleID as MenuID,
	left(m.moduleID,len(m.moduleID)-2) as parentid,
	m.moduleName as caption,
	m.moduleID as [name],
	m.offset as offset,
	(Select Count(*) From WebMenu m1 Where m1.ModuleId like m.ModuleId + '__') as IsSubMenu,
	'' as img,
	moduleOrder 
from WebMenu m 
where ismenu=1 and moduleid<>'' and LEFT(m.moduleID,len(m.moduleid)-2)LIKE @ParentID
AND LEFT(m.moduleID,2)<>CASE WHEN (SELECT SubValue FROM dbo.SysData WHERE SubName='BoolDZT')=0 THEN '15' ELSE '' END
AND LEFT(m.moduleID,2)<>CASE WHEN (SELECT SubValue FROM dbo.SysData WHERE SubName='mposetting')=0 THEN '17' ELSE '' END
and moduleid<>@PtypeUniqueSet
AND left(moduleid,4)<>(case when @usepos='1' then '' else '0409' end)
order by m.moduleOrder
ELSE
BEGIN
	IF @ifjm =1
		select 
			Distinct 
			m.moduleID as MenuID,
			left(m.moduleID,len(m.moduleID)-2) as parentid,
			m.moduleName as caption,
			m.moduleID as [name],
			m.offset as offset,
			(Select Count(*) From WebMenu m1 Where m1.ModuleId like m.ModuleId + '__') as IsSubMenu,
			'' as img,
			moduleOrder 
		from WebMenu m 
		where ismenu=1 and  moduleid<>'' and  LEFT(m.moduleID,len(m.moduleid)-2)LIKE @ParentID
		AND LEFT(m.moduleID,2)<>CASE WHEN (SELECT SubValue FROM dbo.SysData WHERE SubName='BoolDZT')=0 THEN '15' ELSE '' END  --是否显示店帐通受系统配置控制
		AND LEFT(m.moduleID,2)<>CASE WHEN (SELECT SubValue FROM dbo.SysData WHERE SubName='mposetting')=0 THEN '17' ELSE '' END 
		and ifjm=1
		and moduleid<>@PtypeUniqueSet
		AND Exists(select 1 from employeepower e where e.etypeid=@chvOperator AND m.moduleid=e.moduleid or @chvOperator='00000' or m.ispower=0)
		AND left(moduleid,4)<>(case when @usepos='1' then '' else '0409' end)
		order by m.moduleOrder
	ELSE
		select 
			Distinct 
			m.moduleID as MenuID,
			left(m.moduleID,len(m.moduleID)-2) as parentid,
			m.moduleName as caption,
			m.moduleID as [name],
			m.offset as offset,
			(Select Count(*) From WebMenu m1 Where m1.ModuleId like m.ModuleId + '__') as IsSubMenu,
			'' as img,
			moduleOrder 
		from WebMenu m 
		where ismenu=1 and  moduleid<>'' and  LEFT(m.moduleID,len(m.moduleid)-2)LIKE @ParentID
		AND LEFT(m.moduleID,2)<>CASE WHEN (SELECT SubValue FROM dbo.SysData WHERE SubName='BoolDZT')=0 THEN '15' ELSE '' END
		AND LEFT(m.moduleID,2)<>CASE WHEN (SELECT SubValue FROM dbo.SysData WHERE SubName='mposetting')=0 THEN '17' ELSE '' END
		and moduleid<>@PtypeUniqueSet
		AND Exists(select 1 from employeepower e where e.etypeid=@chvOperator AND m.moduleid=e.moduleid or @chvOperator='00000' or m.ispower=0)
		AND left(moduleid,4)<>(case when @usepos='1' then '' else '0409' end)
		order by m.moduleOrder
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].[FZInsertColorSize]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
  DROP PROCEDURE [dbo].[FZInsertColorSize]
GO




/*写入商品颜色或尺码的基本信息  
       0     执行成功  
       －1 执行失败  
       －2  有相同名称的颜色、尺码存在  
    - 3  有相同编码的颜色、尺码存在  
*/  
CREATE  PROCEDURE FZInsertColorSize
  (
    @tablename VARCHAR(1) ,         --输入的表名'C:颜色表，S：为尺码表'  
    @name VARCHAR(30) ,        --设置颜色名称  
    @barcode VARCHAR(230) ,        --相应条码  
    @remark VARCHAR(100) ,       --用户说明  
    @iMode VARCHAR(1) ,         --操作方式  增加A、修改M、删除D
    @csid INT                 --旧的颜色、尺码   
    
  )
AS 
/*
alter by hww 2011年8月17日15:14:04
在删除尺码时，增加对配码包的检查，如果被配码包占用，则不能删除
*/
  DECLARE @colorgroupid INT ,
    @sizegroupid VARCHAR(30) ,
    @oldbar VARCHAR(30)  
  DECLARE @oldBcon VARCHAR(30) ,
    @ptypeid VARCHAR(50) ,
    @formatid VARCHAR(10) ,
    @oobarcode VARCHAR(30)   
  DECLARE @oldCGid INT ,
    @oldSGid INT ,
    @cid INT    
  DECLARE @colorid INT ,
    @cbar VARCHAR(10) ,
    @sieeid INT ,
    @sbar VARCHAR(10) ,
    @bar VARCHAR(50)   
  DECLARE @Stats1 INT  
  DECLARE @Stats2 INT  
  SELECT  @Stats1 = stats
  FROM    syscon
  WHERE   [order] = 81  
  SELECT  @Stats2 = stats
  FROM    syscon
  WHERE   [order] = 82  
  DECLARE @UpdateTag INT
  IF @tablename = 'C' 
    BEGIN  

      IF @iMode = 'A' 
        BEGIN  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   [name] = @name
                              AND @Stats1 = 1 ) 
            GOTO error100 --不允许名称相同  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   [barcode] = @barcode
                              AND @Stats2 = 1 ) 
            GOTO error101--不允许编码相同  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [name] = @name
                              AND barcode = @barcode
                              AND @barcode <> '' ) 
            GOTO error100  
                
          BEGIN TRAN INSERTA  
          EXEC [dbo].[XW_GetUpdateTag] 'Color', @UpdateTag OUTPUT
          INSERT  INTO [color] ( [name], barcode, [remark], updateTag )
          VALUES  ( @name, @barcode, @remark, @UpdateTag )   
          IF @@rowcount = 0
            OR @@Error <> 0 
            BEGIN  
              ROLLBACK TRAN INSERTA  
              GOTO error111  
            END   
          COMMIT TRAN INSERTA  
           --if exists(select [barcode]  from [color]  where colorid <>@csid and [name]=@name and barcode<>@barcode and @barcode <> '')   
           --   goto error106   
          GOTO succee  
        END   
       /*修改颜色*/  
      IF @iMode = 'M' 
        BEGIN  
          IF NOT EXISTS(SELECT 1 FROM dbo.[color] WHERE ColorID = @csid) --判断要操作的信息是否存在
            GOTO error107 
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [name] = @name
                              AND @Stats1 = 1 )--不允许名称相同  
            GOTO error100  
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [barcode] = @barcode
                              AND @Stats2 = 1 )  --不允许编码相同  
            GOTO error101  
                   
          IF EXISTS ( SELECT  [name]
                      FROM    [color]
                      WHERE   colorid <> @csid
                              AND [name] = @name
                              AND barcode = @barcode
                              AND @barcode <> '' ) 
            GOTO error100  
          SELECT  colorgroupID
          INTO    #tmptable
          FROM    colorgroup
          WHERE   colorgroupID IN ( SELECT  colorgroupid
                                    FROM    colorgrouprelation
                                    WHERE   colorid = @csid )
                  AND colorgroupid IN ( SELECT  colorgroupid
                                        FROM    colorgrouprelation
                                        WHERE   colorid IN ( SELECT colorid
                                                             FROM   color
                                                             WHERE  ( [name] = @name
                                                                      OR ( barcode = @barcode
                                                                           AND @barcode <> ''
                                                                         )
                                                                    )
                                                                    AND colorid <> @csid ) )  
          IF EXISTS ( SELECT  *
                      FROM    #tmptable ) 
            BEGIN  
              DROP TABLE #tmptable         
              GOTO error103  
            END  
          DROP TABLE #tmptable      
     
          BEGIN TRAN   
          SELECT  @oldbar = barcode
          FROM    [color]
          WHERE   colorid = @csid  
          EXEC [dbo].[XW_GetUpdateTag] 'Color', @UpdateTag OUTPUT
          UPDATE  [color]
          SET     [name] = @name, barcode = @barcode, [remark] = @remark, updateTag = @UpdateTag
          WHERE   colorid = @csid  
          IF @@rowcount = 0 
            BEGIN  
              ROLLBACK TRAN   
              GOTO error111  
            END  
          IF @oldbar + '1' <> @barcode + '1' --加一个常量字符串，区分是否有尾部空格  
            BEGIN  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + @barcode + ( SELECT BarCode FROM [Size] c WHERE c.SizeId = a.SizeId )
                                           WHEN cspz = 1 THEN b.barcode + @barcode
                                           WHEN cspz = 2 THEN b.barcode + ( SELECT MAX (BarCode) FROM [Size] c WHERE c.SizeId = a.SizeId )
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   colorid = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '1'  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + ( SELECT BarCode FROM [Size] c WHERE c.SizeId = a.SizeId ) + @barcode
                                           WHEN cspz = 1 THEN b.barcode + @barcode
                                           WHEN cspz = 2 THEN b.barcode + ( SELECT MAX (BarCode) FROM [Size] c WHERE c.SizeId = a.SizeId )
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   colorid = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '2'  
            END   
          COMMIT TRAN  
      		    --系统条码修改后，如果存在唯一码，要删除 ptypeuniquecode
          IF @oldbar <> @barcode 
            BEGIN
              DELETE  FROM ptypeuniquecode
              WHERE   ColorID = @csid 
              DELETE  FROM PtypeUniqueCheck
              WHERE   ColorID = @csid 
            END
          GOTO succee  
        END  
      IF @iMode = 'D' 
        BEGIN  
          IF @csid = '1' 
            GOTO succee  
           
           if exists(select * from BakDly where ColorId =@csid) or
              exists(select * from DlyData where ColorId =@csid) or
              exists(select * from IniGoodsDetail where ColorId =@csid) or
              exists(select * from Goodsstockdetail where ColorId =@csid) or
              exists(select * from BakDlyOrder where ColorId =@csid) 
           GOTO error100  
          --不判断此处了，可以直接删除
          --IF EXISTS ( SELECT  *
          --            FROM    ptypecolor
          --            WHERE   colorid = @csid ) 
          --  GOTO error100  

          --IF EXISTS ( SELECT  *
          --            FROM    ColorGroupRelation
          --            WHERE   colorid = @csid ) 
          --  GOTO error100  
          --  ELSE 
          IF EXISTS(SELECT 1 FROM dbo.AutoPhGrdData WHERE PCTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF EXISTS(SELECT 1 FROM dbo.AutoPhOrderGrdData WHERE PCTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF NOT EXISTS(SELECT 1 FROM dbo.[color] WHERE ColorID = @csid) --判断要删除的信息是否不存在
            GOTO error107 
            
          ELSE 
            BEGIN  
              BEGIN TRAN D  
              DELETE  FROM [color]
              WHERE   colorid = @csid  
              IF @@error <> 0 
                BEGIN  
                  ROLLBACK TRAN D  
                  GOTO error111  
                END  
            delete from ColorGroupRelation where ColorId =@csid 
			delete from ColorGroup where not exists(select * from ColorGroupRelation where ColorId=@csid and ColorGroupID=ColorGroup.ColorGroupID)
			--商品颜色处替换,没有颜色了，替换成均色
          	update PType set ColorIdList='1',ColorGroupid=1,CSPZ =case when SizeGroupid=1 then 3 else 2 end
			where REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',',') in (',',',,') and 
			exists(select * from PtypeColor  where ColorId=@csid and PtypeId=ptype.TypeID)


			update PType set ColorIdList=
				case when left(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),1)=',' 
				then 
					case when RIGHT(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),1)=',' 
						then SUBSTRING(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),2,len(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','))-2)
					else
						RIGHT(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),len(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','))-1)			
					end
				else
					case when RIGHT(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),1)=',' 
						then SUBSTRING(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',','),0,len(REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',',')))
					else 
						REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',',')
					end
				end
			where REPLACE(','+ColorIdList+',',','+CONVERT(varchar(10),@csid)+',',',') not in (',',',,') and 
			exists(select * from PtypeColor  where ColorId=@csid and PtypeId=ptype.TypeID)         
			select PtypeId into #ptypeColor from ptypecolor where ColorId =@csid 
			delete from ptypecolor where ColorId =@csid
			delete from PtypeBar where ColorId =@csid  --条码表
			delete from MultiBarList where ColorId =@csid   --对照码表
			
			declare @FormatidT int,@typeId varchar(50),@cspz int,@BarcodeT VARCHAR(30),@ColorIdList VARCHAR(1000),@SizeIdList VARCHAR(1000),@AttributeId1 INT,@AttributeId2 INT,@AttributeId3 INT,@AttributeId4 INT,@AttributeId5 INT,@AttributeId6 INT,@AttributeId7 INT,@AttributeId8 INT,@Btypeid varchar(50)   
			SET @Btypeid =''
			if exists(select * from #ptypeColor where  ptypeid not IN (select PtypeId from ptypecolor))			
			BEGIN
				declare abc cursor for select formatid,typeid,cspz,barcode,coloridlist,sizeidlist,btypeid1 from ptype p 
				inner join #ptypeColor b on p.typeid=b.ptypeid  where b.ptypeid not IN (select PtypeId from ptypecolor)
				open abc
				fetch next from abc into @FormatidT,@typeId,@cspz,@BarcodeT,@ColorIdList,@SizeIdList,@btypeid
				while @@FETCH_STATUS =0
				BEGIN
					SET @AttributeId1=0
					SET @AttributeId2=0
					SET @AttributeId3=0
					SET @AttributeId4=0
					SET @AttributeId5=0
					SET @AttributeId6=0
					SET @AttributeId7=0
					SET @AttributeId8=0
					select @AttributeId1=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =1
					select @AttributeId2=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =2
					select @AttributeId3=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =3
					select @AttributeId4=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =4
					select @AttributeId5=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =5
					select @AttributeId6=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =6
					select @AttributeId7=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =7
					select @AttributeId8=isnull(a.AttributeId,0) from PtypeAttribute a inner join AssistAttribute b on a.AttributeID =b.AttributeId where a.PtypeId=@typeId and b.TypeID =8
					EXEC GeneratePtypeBar @FormatidT,@typeId,@cspz,@BarcodeT,@ColorIdList,@SizeIdList,@AttributeId1,@AttributeId2,@AttributeId3,@AttributeId4,@AttributeId5,@AttributeId6,@AttributeId7,@AttributeId8,@Btypeid    
					fetch next from abc into @FormatidT,@typeId,@cspz,@BarcodeT,@ColorIdList,@SizeIdList,@btypeid
				END
				CLOSE ABC
				deallocate ABC
			END
			--插入均色
			insert into PtypeColor(PtypeId,ColorId) select PtypeId,1 from #ptypeColor where  ptypeid not IN (select PtypeId from ptypecolor) 
			DROP TABLE #ptypeColor

              IF @@error <> 0 
                BEGIN  
                  ROLLBACK TRAN D  
                  GOTO error111  
                END  
              COMMIT TRAN D  
              GOTO succee  
            END  
        END  
    END  
  IF @tablename = 'S' 
    BEGIN  
      IF @iMode = 'A' 
        BEGIN    
          IF EXISTS ( SELECT  [name]
                      FROM    [size]
                      WHERE   [name] = @name
                              AND @Stats1 = 1 ) 
            GOTO error100 --不允许名称相同  
          IF EXISTS ( SELECT  [name]
                      FROM    [size]
                      WHERE   [barcode] = @barcode
                              AND @Stats2 = 1 ) 
            GOTO error101--不允许编码相同  
          IF EXISTS ( SELECT  *
                      FROM    [size]
                      WHERE   [name] = @name
                              AND barcode = @barcode
                              AND @barcode <> '' ) 
            GOTO error100  
        
          BEGIN TRAN INSERTA  
          EXEC [dbo].[XW_GetUpdateTag] 'Size', @UpdateTag OUTPUT
          INSERT  INTO [size] ( [name], barcode, remark, updateTag )
          VALUES  ( @name, @barcode, @remark, @UpdateTag )   
          IF @@rowcount = 0 
            BEGIN  
              ROLLBACK TRAN INSERTA  
              GOTO error111  
            END   
          COMMIT TRAN INSERTA  
                     --if exists(Select * from [size] where [name]=@name and barcode <> @barcode and @barcode <> '')    
                      --  goto error106  
          GOTO succee  
        END  
    
      IF @iMode = 'M' 
        BEGIN  
          IF NOT EXISTS(SELECT 1 FROM dbo.[SIZE] WHERE SizeID = @csid) --判断要操作的信息是否存在
            GOTO error107 
          IF EXISTS ( SELECT  1
                      FROM    [size]
                      WHERE   sizeid <> @csid
                              AND [name] = @name
                              AND @Stats1 = 1 )--不允许名称相同  
            GOTO error100  
          IF EXISTS ( SELECT  1
                      FROM    [size]
                      WHERE   sizeid <> @csid
                              AND [barcode] = @barcode
                              AND @Stats2 = 1 )  --不允许编码相同  
            GOTO error101  
          IF EXISTS ( SELECT  *
                      FROM    [size]
                      WHERE   [name] = @name
                              AND BarCode = @barcode
                              AND sizeid <> @csid
                              AND @barcode <> '' ) 
            GOTO error100  
      
          SELECT  sizegroupID
          INTO    #tmptables
          FROM    sizegroup
          WHERE   sizegroupID IN ( SELECT sizegroupID
                                   FROM   Sizegrouprelation
                                   WHERE  sizeid = @csid )
                  AND sizegroupID IN ( SELECT sizegroupID
                                       FROM   Sizegrouprelation
                                       WHERE  sizeid IN ( SELECT  sizeid
                                                          FROM    size
                                                          WHERE   ( [name] = @name
                                                                    OR ( barcode = @barcode
                                                                         AND @barcode <> ''
                                                                       )
                                                                  )
                                                                  AND sizeid <> @csid ) )  
          IF EXISTS ( SELECT  *
                      FROM    #tmptables ) 
            BEGIN  
              DROP TABLE #tmptables         
              GOTO error103  
            END  
          DROP TABLE #tmptables         
          BEGIN TRAN   
          SELECT  @oldbar = barcode
          FROM    [size]
          WHERE   sizeid = @csid  
          EXEC [dbo].[XW_GetUpdateTag] 'Size', @UpdateTag OUTPUT
          UPDATE  [size]
          SET     [name] = @name, barcode = @barcode, [remark] = @remark, updateTag = @UpdateTag
          WHERE   sizeid = @csid  
          IF @@rowcount = 0 
            BEGIN  
              ROLLBACK TRAN   
              GOTO error111  
            END  
          IF EXISTS ( SELECT  *
                      FROM    sizegrouprelation sg ,
                              size s
                      WHERE   s.sizeid = sg.sizeid
                              AND sg.sizeid = @csid
                              AND ( s.name = @name )
                              AND sizegroupid IN ( SELECT sg.sizegroupid
                                                   FROM   sizegrouprelation sg ,
                                                          size s
                                                   WHERE  s.sizeid = sg.sizeid
                                                          AND s.Name = @name
                                                          AND sg.sizeid <> @csid ) ) 
            BEGIN  
              ROLLBACK TRAN   
              GOTO error103   
            END  
   
    
          IF @oldbar <> @barcode 
            BEGIN  
--如果条码变动,则更新条码信息  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid ) + @barcode
                                           WHEN cspz = 1 THEN b.barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid )
                                           WHEN cspz = 2 THEN b.barcode + @barcode
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   SizeID = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '1'  
              UPDATE  PtypeBar
              SET     FullbarCode = ( CASE WHEN cspz = 0 THEN b.barcode + @barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid )
                                           WHEN cspz = 1 THEN b.barcode + ( SELECT BarCode FROM Color c WHERE c.Colorid = a.Colorid )
                                           WHEN cspz = 2 THEN b.barcode + @barcode
                                           ELSE b.barcode
                                      END )
              FROM    ptypebar a ,
                      Ptype b
              WHERE   SizeID = @csid
                      AND a.ptypeid = b.typeid
                      AND b.formatid = '2'  
            END  
          COMMIT TRAN  
                    
      		    --系统条码修改后，如果存在唯一码，要删除 ptypeuniquecode
          IF @oldbar <> @barcode 
            BEGIN
              DELETE  FROM ptypeuniquecode
              WHERE   SizeID = @csid 
              DELETE  FROM PtypeUniqueCheck
              WHERE   SizeID = @csid 
            END
          GOTO succee  
        END   
     
    
      IF @iMode = 'D' 
        BEGIN  
          IF @csid = '1' 
            GOTO succee  
          IF EXISTS ( SELECT  *
                      FROM    ptypesize
                      WHERE   sizeid = @csid ) 
            GOTO error100  
          IF EXISTS ( SELECT  *
                      FROM    SizeGroupRelation
                      WHERE   sizeid = @csid ) 
            GOTO error100  
          ELSE IF EXISTS(SELECT 1 FROM dbo.PMdetail WHERE PSTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF EXISTS(SELECT 1 FROM dbo.AutoPhGrdData WHERE PSTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF EXISTS(SELECT 1 FROM dbo.AutoPhOrderGrdData WHERE PSTypeID = @csid) --增加对配码包的检查
            GOTO error100 
          ELSE IF NOT EXISTS(SELECT 1 FROM dbo.[SIZE] WHERE SizeId = @csid) --判断要删除的信息是否不存在
            GOTO error107
          ELSE           
            BEGIN  
                                                          
              BEGIN TRAN D  
              DELETE  FROM [size]
              WHERE   sizeid = @csid  
              IF @@error <> 0 
                BEGIN  
                  ROLLBACK TRAN D  
                  GOTO error111  
                END  
              DELETE  FROM SizeGROUPRELATION
              WHERE   sizeid = @csid  
              IF @@error <> 0 
                BEGIN  
                  ROLLBACK TRAN D  
                  GOTO error111  
                END  
              COMMIT TRAN D  
              GOTO succee  
            END  
        END  
    END   
  succee:  
               
  RETURN 0  
  error111:  
  RETURN -1  
  error100:  
  RETURN -2  
  error101:  
  RETURN -3  
  error102:  
  RETURN -4  
  error103:  
  RETURN -5 --在一个商品中存在颜色名称相同的记录  
  error106:  
  RETURN 1
 --相同颜色不同条码  
  error107:  
  RETURN -7 --删除的信息不存在



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/******************************************20130702********************************************/
/*1、凭证导出接口增加机构的查询条件
  2、店账通更换接口
*/
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZGetFinanceData]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZGetFinanceData]
GO


CREATE PROCEDURE FZGetFinanceData
    (
      @ctypeid VARCHAR(1500),
      @begindate VARCHAR(10) ,
      @EndDate VARCHAR(10) ,
      @unite BIT --1:要合并当天的单据 0：不合并
    )
AS 
    IF @begindate > @Enddate 
        BEGIN
            SELECT  'A'
            RETURN -1 --设置日期不正确
        END

     --资产合计  【支出类】为正为借方 为负为贷方		 --【负债合计】【收入类】为正为贷方 为负为借方		



    IF @unite = 1 
        BEGIN
            SELECT  number ,
                    date ,
                    bname1 ,
                    bname2 ,
                    ename ,
                    dmname ,
                    SUM(c.Total) Total ,
                    SUM(c.Total2) Total2 ,
                    ufusercode ,
                    summary ,
                    type,usercode
            FROM    ( SELECT    number ,
                                date ,
                                bname1 ,
                                bname2 ,
                                ename ,
                                dmname ,
                                CASE a.Total
                                  WHEN 0 THEN 2
                                  ELSE 1
                                END AS type ,
                                a.Total ,
                                ( a.Total2 ) Total2 ,
                                ufusercode ,
                                summary,usercode
                      FROM      ( SELECT    dn.number ,
                                            da.[date] ,
                                            ( SELECT    fullname
                                              FROM      btype b
                                              WHERE     b.typeid = da.btypeid
                                                        AND LEFT(da.btypeid, 5) IN (
                                                        '00001', '00007' )
                                            ) bName1 ,
                                            ( SELECT    fullname
                                              FROM      btype b
                                              WHERE     b.typeid = da.btypeid
                                                        AND LEFT(da.btypeid, 5) IN (
                                                        '00002', '00004',
                                                        '00003','00006' )
                                            ) bName2 ,
                                            ( SELECT    fullname
                                              FROM      employee e
                                              WHERE     E.typeid = da.etypeid
                                            ) EName ,
                                            ( SELECT    fullname
                                              FROM      department dm
                                              WHERE     dm.typeid = dn.Dtypeid
                                            ) DMName ,
                                            CASE WHEN LEFT(da.atypeid, 5) IN (
                                                      '00001', '00004',
                                                      '00007' )
                                                      AND da.total > 0
                                                 THEN ABS(da.Total)
                                                 WHEN LEFT(da.atypeid, 5) IN (
                                                      '00002', '00003' )
                                                      AND da.total < 0
                                                 THEN ABS(da.Total)
                                                 ELSE 0
                                            END AS Total ,
                                            CASE WHEN LEFT(da.atypeid, 5) IN (
                                                      '00001', '00004',
                                                      '00007' )
                                                      AND da.total < 0
                                                 THEN ABS(da.Total)
                                                 WHEN LEFT(da.atypeid, 5) IN (
                                                      '00002', '00003' )
                                                      AND da.total > 0
                                                 THEN ABS(da.Total)
                                                 ELSE 0
                                            END AS Total2 ,
                                            da.ufusercode ,
                                            summary,da.usercode
                                  FROM      dlyndx dn ,
                                            ( SELECT    da.* ,
                                                        a.rec AS ufusercode,a.usercode
                                              FROM      dlya da ,
                                                        atype a
                                              WHERE     da.branchid = a.branchid
                                                        AND da.atypeid = a.typeid
							and da.total <> 0
                                            ) da
                                  WHERE     dn.redold = 'F'
											AND EXISTS(SELECT 1 FROM dbo.fn_split(@ctypeid,',') t WHERE dn.branchid LIKE t.a+'%') 
                                           -- AND dn.VchType NOT IN ( 232, 234 )
                                            AND dn.vchcode = da.vchcode
                                            AND dn.date BETWEEN @Begindate AND @EndDate
                                ) a
                    ) AS c
            GROUP BY number ,
                    [date] ,
                    bname1 ,
                    bname2 ,
                    ename ,
                    dmname ,
                    ufusercode ,
                    summary ,
                    type,usercode
		ORDER BY number                    
            IF @@rowcount = 0  --没有记录
                BEGIN	
                    SELECT  'A'
                    RETURN -2
                END
            ELSE 
                RETURN 0
        END
    ELSE 
        BEGIN
            SELECT  dn.number ,
                    da.[date] ,
                    ( SELECT    fullname
                      FROM      btype b
                      WHERE     b.typeid = da.btypeid
                                AND LEFT(da.btypeid, 5) IN ( '00001', '00007' )
                    ) bName1 ,
                    ( SELECT    fullname
                      FROM      btype b
                      WHERE     b.typeid = da.btypeid
                                AND LEFT(da.btypeid, 5) IN ( '00002', '00004',
                                                             '00003','00006' )
                    ) bName2 ,
                    ( SELECT    fullname
                      FROM      employee e
                      WHERE     E.typeid = da.etypeid
                    ) EName ,
                    ( SELECT    fullname
                      FROM      department dm
                      WHERE     dm.typeid = dn.Dtypeid
                    ) DMName ,
                    CASE WHEN LEFT(da.atypeid, 5) IN ( '00001', '00004',
                                                       '00007' )
                              AND da.total > 0 THEN ABS(da.Total)
                         WHEN LEFT(da.atypeid, 5) IN ( '00002', '00003' )
                              AND da.total < 0 THEN ABS(da.Total)
                         ELSE 0
                    END AS Total ,
                    CASE WHEN LEFT(da.atypeid, 5) IN ( '00001', '00004',
                                                       '00007' )
                              AND da.total < 0 THEN ABS(da.Total)
                         WHEN LEFT(da.atypeid, 5) IN ( '00002', '00003' )
                              AND da.total > 0 THEN ABS(da.Total)
                         ELSE 0
                    END AS Total2 ,
                    da.ufusercode ,
                    summary,da.usercode
            FROM    dlyndx dn ,
                    ( SELECT    da.* ,
                                a.rec AS ufusercode,
				a.usercode
                      FROM      dlya da ,
                                atype a
                      WHERE     da.branchid = a.branchid
                                AND da.atypeid = a.typeid
				and da.total <> 0
                    ) da
            WHERE   dn.redold = 'F'
					AND EXISTS(SELECT 1 FROM dbo.fn_split(@ctypeid,',') t WHERE dn.branchid LIKE t.a+'%') 
                   -- AND dn.VchType NOT IN ( 232, 234 )
                    AND dn.vchcode = da.vchcode
                    AND dn.date BETWEEN @Begindate AND @EndDate
		   ORDER BY number  
            IF @@rowcount = 0  --没有记录
                BEGIN	
                    SELECT  'A'
                    RETURN -2
                END
            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].[FZGetCurrentTotal]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
  DROP PROCEDURE [dbo].[FZGetCurrentTotal]
GO




--取得在某一个时间一个或一类商品的库存，一个单位的应收余额，一个科目的余额
CREATE  PROCEDURE FZGetCurrentTotal
(
 @szSelect VARCHAR(50),
 @szAtypeid VARCHAR(50),
 @szPtypeid VARCHAR(50),
 @szBtypeid VARCHAR(50),
 @szEtypeid VARCHAR(50),
 @szKtypeid VARCHAR(50),
 @Enddate VARCHAR(10),
 @dQty NUMERIC(24, 10) OUTPUT,
 @dTotal NUMERIC(24, 10) OUTPUT,
 @BranchId VARCHAR(50),
 @OperatorId VARCHAR(50),
 @IsStop BIT = 0,--是否包含停用商品 0：包含  1：不包含
 @includeYS BIT = 0 ,	--是否包含预收款 ：1包含 0不包含
 @includeYF BIT = 0	--是否包含预付款 ：1包含 0不包含    
)
AS 
DECLARE @AR_ID VARCHAR(50)
DECLARE @AP_ID VARCHAR(50)
DECLARE @dTempAr NUMERIC(24, 10)
DECLARE @dTempAp NUMERIC(24, 10),
	@PreAr NUMERIC(24, 10),
	@PreAp NUMERIC(24, 10),
	@FZCS int
DECLARE @nPSon INT
DECLARE @nBSon INT
SELECT  @AR_ID = '0000100005'
SELECT  @AP_ID = '0000200001'

IF EXISTS(SELECT * FROM sysdata WHERE SubName = 'proctypename' AND SubValue = 'FZCS')
SELECT @FZCS = 1
ELSE SELECT @FZCS = 0
    
IF @szSelect = 'btype' 
  BEGIN
    SELECT  @nBSon = [sonnum]
    FROM    btype
    WHERE   [typeid] = (CASE @szBtypeid
                          WHEN '' THEN '00000'
                          ELSE @szBtypeid
                        END)
    IF @nBSon > 0 
      BEGIN
        SELECT  @dTotal = ISNULL(SUM(CASE atypeid WHEN '0000200888' THEN -total ELSE total end), 0)
        FROM    dlya
        WHERE   [date] >= @Enddate AND RedOld = 'F'
                AND btypeid LIKE @szBtypeid + '%'
                AND ((atypeid = @AR_ID AND @includeYS = 0) OR ((atypeid = @AR_ID OR atypeid = '0000200888') AND @includeYS = 1))
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = dlya.branchid ))
                	OR
                	(@FZCS = 1 AND dlya.branchid LIKE @BranchId + '%')
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = dlya.BranchID
                                    AND iniover = 1 )
                            
        SELECT  @dQty = ISNULL(SUM(CASE atypeid WHEN '0000100888' THEN -total ELSE total end), 0)
        FROM    dlya
        WHERE   [date] >= @Enddate AND RedOld = 'F'
                AND btypeid LIKE @szBtypeid + '%'
                AND ((atypeid = @Ap_ID AND @includeYF = 0) OR ((atypeid = @Ap_ID OR atypeid = '0000100888') AND @includeYF = 1))
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = dlya.branchid ))
                	OR
                	(@FZCS = 1 AND dlya.branchid LIKE @BranchId + '%')
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = dlya.BranchID
                                    AND iniover = 1 )
                            
        SELECT  @dTotal = @dTotal - @dQty
        SELECT  @dTempAr = ISNULL(SUM(bb.artotal), 0),
                @dTempAp = ISNULL(SUM(bb.aptotal), 0),
                @PreAr = SUM(ISNULL(bb.deposit,0)),
                @PreAp = SUM(ISNULL(bb.prepayment,0))
                --SELECT * FROM dbo.BranchBtype
        FROM    btype b
        LEFT JOIN BranchBtype bb
        ON      b.TypeId = bb.Btypeid
                AND bb.BranchId LIKE @BranchID + '%'
        WHERE   b.typeid LIKE @szBtypeid + '%'
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = bb.branchid ))
                	OR
                	(@FZCS = 1 AND 1=1)
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = bb.BranchID
                                    AND iniover = 1 )
          
        SELECT  @dTotal = (@dTempAr - @dTempAp) - @dTotal
        IF   @includeYF = 1 SELECT @dTotal = @dTotal + @PreAp
        IF   @includeYS = 1 SELECT @dTotal = @dTotal - @PreAr
        SELECT  @dQty = @dTotal
        RETURN 0
      END
    ELSE 
      BEGIN
        SELECT  @dTotal = ISNULL(SUM(CASE atypeid WHEN '0000200888' THEN -total ELSE total end), 0)
        FROM    dlya
        WHERE   [date] >= @Enddate AND RedOld = 'F'
                AND btypeid = @szBtypeid
                AND ((atypeid = @AR_ID AND @includeYF = 0) OR ((atypeid = @AR_ID OR atypeid = '0000200888') AND @includeYF = 1))
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = dlya.branchid ))
                	OR
                	(@FZCS = 1 AND dlya.branchid LIKE @BranchId + '%')
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = dlya.BranchID
                                    AND iniover = 1 )
                            
        SELECT  @dQty = ISNULL(SUM(CASE atypeid WHEN '0000100888' THEN -total ELSE total end), 0)
        FROM    dlya
        WHERE   [date] >= @Enddate AND RedOld = 'F'
                AND btypeid = @szBtypeid
                AND ((atypeid = @Ap_ID AND @includeYF = 0) OR ((atypeid = @Ap_ID OR atypeid = '0000100888') AND @includeYF = 1))
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = dlya.branchid ))
                	OR
                	(@FZCS = 1 AND dlya.branchid LIKE @BranchId + '%')
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = dlya.BranchID
                                    AND iniover = 1 )
                            
        SELECT  @dTotal = @dTotal - @dQty
        SELECT  @dTempAr = ISNULL(SUM(bb.artotal), 0),
                @dTempAp = ISNULL(SUM(bb.aptotal), 0),
                @PreAr = SUM(ISNULL(bb.deposit,0)),
                @PreAp = SUM(ISNULL(bb.prepayment,0))
        FROM    btype b
        LEFT JOIN BranchBtype bb
        ON      b.TypeId = bb.Btypeid
                AND bb.BranchId LIKE @BranchID + '%'
        WHERE   b.typeid = @szBtypeid
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = bb.branchid ))
                	OR
                	(@FZCS = 1 AND 1=1)
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = bb.BranchID
                                    AND iniover = 1 )
                            
        SELECT  @dTotal = (@dTempAr - @dTempAp) - @dTotal
        IF   @includeYF = 1 SELECT @dTotal = @dTotal + @PreAp
        IF   @includeYS = 1 SELECT @dTotal = @dTotal - @PreAr
        SELECT  @dQty = @dTotal
        RETURN 0
      END
  END
-------------------------------------------------------
IF @szSelect = 'etype' 
  BEGIN
    SELECT  @nBSon = [sonnum]
    FROM    employee
    WHERE   [typeid] = @szEtypeid
    IF @nBSon > 0
      AND @szEtypeid <> '00000' 
      BEGIN
        SELECT  @dTotal = SUM(ISNULL(total, 0))
        FROM    dlya
        WHERE   [date] <= @Enddate AND RedOld = 'F'
                AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                AND atypeid IN (@AR_ID, @AP_ID)  
        SELECT  @dQty = SUM(ISNULL(total, 0))
        FROM    dlya
        WHERE   [date] <= @Enddate AND RedOld = 'F'
                AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                AND atypeid IN (@AR_ID, @AP_ID)
        IF @dQty > 0 
          SELECT  @dTotal = -@dQty

        IF LEFT(@szBtypeid, 5) = '00001'
          AND @szatypeid = '0000200001' --应付
          BEGIN
            SELECT  @dTotal = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000200001'
            SELECT  @dTempAp = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000100005'
            SELECT  @dTempAp = ISNULL(@dTempAp, 0)
            SELECT  @dTotal = -(@dTotal - @dTempAp)

          END
        IF LEFT(@szBtypeid, 5) <> '00001'
          AND @szatypeid = '0000100005' --应收
          BEGIN
            SELECT  @dQty = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000100005'
            SELECT  @dTempAp = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000200001'
            SELECT  @dTempAp = ISNULL(@dTempAp, 0)
            SELECT  @dQty = ISNULL(@dQty, 0) - @dTempAp

          END
        IF @dQty <> 0 
          SELECT  @dTotal = @dQty
        SELECT  @dTotal = ISNULL(@dTotal, 0)
        SELECT  @dQty = ISNULL(@dQty, 0)
      END
    ELSE 
      BEGIN
        IF LEFT(@szBtypeid, 5) = '00001'
          AND @szatypeid = '0000200001' --应付
          BEGIN
            SELECT  @dTotal = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND etypeid = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000200001'
            SELECT  @dTempAp = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND etypeid = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000100005'
            SELECT  @dTempAp = ISNULL(@dTempAp, 0)
            SELECT  @dTotal = -(ISNULL(@dTotal, 0) - @dTempAp)

          END
        IF LEFT(@szBtypeid, 5) <> '00001'
          AND @szatypeid = '0000100005' --应收
          BEGIN
            SELECT  @dQty = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND etypeid = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000100005'
            SELECT  @dTempAp = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND etypeid = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000200001'
            SELECT  @dTempAp = ISNULL(@dTempAp, 0)
            SELECT  @dQty = @dQty - @dTempAp

          END
        IF @dQty <> 0 
          SELECT  @dTotal = @dQty
        SELECT  @dTotal = ISNULL(@dTotal, 0)
        SELECT  @dQty = ISNULL(@dQty, 0)
        RETURN 0
      END
  END
-----------------------------------------------------------
ELSE 
  IF @szSelect = 'ptype' 
    BEGIN
      SELECT  @nPSon = sonnum
      FROM    ptype
      WHERE   typeid = @szPtypeid
      IF @szKtypeid = '00000' 
        SET @szKtypeid = ''
      IF @szBtypeid = '00000' 
        SET @szBtypeid = ''
      IF @szKtypeid <> '00000'
        AND @szKtypeid <> '99999' 
        BEGIN
          IF @nPSon > 0 
            BEGIN
              SELECT  @dQty = ISNULL(SUM(qty), 0),
                      @dTotal = ISNULL(SUM(total), 0)
              FROM    goodsstocks a
              INNER JOIN Ptype p
              ON      a.PtypeId = p.TypeID
              WHERE   EXISTS ( SELECT 1
                               FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                               WHERE  Ktypeid = a.Ktypeid )
                      AND LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                      AND p.Stop IN (CASE @IsStop
                                       WHEN 0 THEN p.stop
                                       ELSE 0
                                     END)--是否包含停用商品

              SELECT  @dTempar = ISNULL(SUM(qty), 0),
                      @dTempap = ISNULL(SUM(costtotal), 0)
              FROM    DlyData a
              INNER JOIN Ptype p
              ON      a.PtypeId = p.TypeID
              WHERE   [date] >= @enddate  AND a.RedOld = 'F'
                      AND EXISTS ( SELECT 1
                                   FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                   WHERE  Ktypeid = a.Ktypeid )
                      AND LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                      AND pdetail <> 2
                      AND Vchtype NOT IN ('73', '89')
                      AND p.Stop IN (CASE @IsStop
                                       WHEN 0 THEN p.stop
                                       ELSE 0
                                     END)--是否包含停用商品
                                        
              SELECT  @dQty = ISNULL(@dQty, 0) - ISNULL(@dTempar, 0)
              SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)
            END
          ELSE 
            BEGIN
              SELECT  @dQty = ISNULL(SUM(qty), 0),
                      @dTotal = ISNULL(SUM(total), 0)
              FROM    goodsstocks a
              WHERE   EXISTS ( SELECT 1
                               FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid) s
                               WHERE  s.Ktypeid = a.Ktypeid )
                      AND ptypeid = @szPtypeid

              SELECT  @dTempar = ISNULL(SUM(qty), 0),
                      @dTempap = ISNULL(SUM(costtotal), 0)
              FROM    DlyData a
              WHERE   [date] >= @enddate AND a.RedOld = 'F'
                      AND EXISTS ( SELECT 1
                                   FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid) s
                                   WHERE  s.Ktypeid = a.Ktypeid )
                      AND ptypeid = @szPtypeid
                      AND pdetail <> 2
                      AND Vchtype NOT IN ('73', '89')
                                                                             
              SELECT  @dQty = ISNULL(@dQTy, 0) - ISNULL(@dTempar, 0)
              SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)
            END
        END
      ELSE 
        IF @szKtypeid <> '99999' 
          BEGIN
            IF @nPSon > 0 
              BEGIN
                SELECT  @dQty = ISNULL(SUM(qty), 0),
                        @dTotal = ISNULL(SUM(total), 0)
                FROM    goodsstocks a
                INNER JOIN Ptype p
                ON      a.PtypeId = p.TypeID
                WHERE   LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                        AND EXISTS ( SELECT 1
                                     FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                     WHERE  Ktypeid = a.Ktypeid )
                        AND p.Stop IN (CASE @IsStop
                                         WHEN 0 THEN p.stop
                                         ELSE 0
                                       END)--是否包含停用商品
                                                                                
                SELECT  @dTempar = ISNULL(SUM(qty), 0),
                        @dTempap = ISNULL(SUM(costtotal), 0)
                FROM    DlyData a
                INNER JOIN Ptype p
                ON      a.PtypeId = p.TypeID
                WHERE   [date] >= @enddate AND a.RedOld = 'F'
                        AND EXISTS ( SELECT 1
                                     FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                     WHERE  Ktypeid = a.Ktypeid )
                        AND LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                        AND pdetail <> 2
                        AND Vchtype NOT IN ('73', '89')
                        AND p.Stop IN (CASE @IsStop
                                         WHEN 0 THEN p.stop
                                         ELSE 0
                                       END)--是否包含停用商品

                SELECT  @dQty = ISNULL(@dQTy, 0) - ISNULL(@dTempar, 0)
                SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)
              END
            ELSE 
              BEGIN
                SELECT  @dQty = ISNULL(SUM(qty), 0),
                        @dTotal = ISNULL(SUM(total), 0)
                FROM    goodsstocks a
                WHERE   ptypeid = @szPtypeid
                        AND EXISTS ( SELECT 1
                                     FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                     WHERE  Ktypeid = a.Ktypeid )
                                                                                        
                SELECT  @dTempar = ISNULL(SUM(qty), 0),
                        @dTempap = ISNULL(SUM(costtotal), 0)
                FROM    DlyData a
                WHERE   [date] >= @enddate AND a.RedOld = 'F'
                        AND ptypeid = @szPtypeid
                        AND pdetail <> 2
                        AND Vchtype NOT IN ('73', '89')
                        AND EXISTS ( SELECT 1
                                     FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                     WHERE  Ktypeid = a.Ktypeid )
                                            
                SELECT  @dQty = ISNULL(@dQTy, 0) - ISNULL(@dTempar, 0)
                SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)
              END
          END
        ELSE 
          IF @szKtypeid = '99999' 
            BEGIN
              IF @nPSon > 0 
                BEGIN

                  SELECT  @dQty = ISNULL(SUM(qty), 0),
                          @dTotal = ISNULL(SUM(total), 0)
                  FROM    goodsstocks a
                  INNER JOIN Ptype p
                  ON      a.PtypeId = p.TypeID
                  WHERE   EXISTS ( SELECT 1
                                   FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                   WHERE  Ktypeid = a.Ktypeid )
                          AND LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                          AND p.Stop IN (CASE @IsStop
                                           WHEN 0 THEN p.stop
                                           ELSE 0
                                         END)--是否包含停用商品
                                                
                  SELECT  @dTempar = ISNULL(SUM(qty), 0),
                          @dTempap = ISNULL(SUM(costtotal), 0)
                  FROM    DlyData a
                  INNER JOIN Ptype p
                  ON      a.PtypeId = p.TypeID
                  WHERE   [date] >= @enddate AND a.RedOld = 'F'
                          AND EXISTS ( SELECT 1
                                       FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                       WHERE  Ktypeid = a.Ktypeid )
                          AND LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                          AND pdetail <> 2
                          AND Vchtype NOT IN ('73', '89')
                          AND p.Stop IN (CASE @IsStop
                                           WHEN 0 THEN p.stop
                                           ELSE 0
                                         END)--是否包含停用商品
                                                
                  SELECT  @dQty = ISNULL(@dQTy, 0) - ISNULL(@dTempar, 0)
                  SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)
                END
              ELSE 
                BEGIN

                  SELECT  @dQty = ISNULL(SUM(qty), 0),
                          @dTotal = ISNULL(SUM(total), 0)
                  FROM    goodsstocks a
                  WHERE   EXISTS ( SELECT 1
                                   FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                   WHERE  Ktypeid = a.Ktypeid )
                          AND ptypeid = @szPtypeid  
                                                                                                
                  SELECT  @dTempar = ISNULL(SUM(qty), 0),
                          @dTempap = ISNULL(SUM(costtotal), 0)
                  FROM    DlyData a
                  WHERE   [date] >= @enddate AND a.RedOld = 'F'
                          AND EXISTS ( SELECT 1
                                       FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                       WHERE  Ktypeid = a.Ktypeid )
                          AND ptypeid = @szPtypeid
                          AND pdetail <> 2
                          AND Vchtype NOT IN ('73', '89')
                                                                                                
                  SELECT  @dQty = ISNULL(@dQTy, 0) - ISNULL(@dTempar, 0)
                  SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)              
                END
            END
      RETURN 0	
    END
  ELSE 
    IF @szSelect = 'atype' 
      BEGIN
        SELECT  @dTotal = ISNULL(SUM(total + TTL00), 0)
        FROM    atype
        WHERE   EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangeBCList(@OperatorId, @BranchId)
                         WHERE  BranchID = atype.branchid )
                AND LEFT(typeid, LEN(@szatypeid)) = @szAtypeID
                            
        SELECT  @dTempar = ISNULL(SUM(total), 0)
        FROM    dlya
        WHERE   EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangeBCList(@OperatorId, @BranchId)
                         WHERE  BranchID = dlya.branchid )
                AND [date] >= @enddate
                AND LEFT(atypeid, LEN(@szatypeid)) = @szAtypeid
                 AND RedOld = 'F'
                            
        SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempar, 0)
        SELECT  @dQty = ISNULL(@dTotal, 0)
        RETURN 0
      END
    ELSE 
      IF @szSelect = 'employee' 
        BEGIN  
          SELECT  @dTotal = ISNULL(SUM([total]), 0)
          FROM    dlya
          WHERE   [etypeid] = @szEtypeid AND RedOld = 'F'
                  AND [atypeid] = @szAtypeid
                  AND [btypeid] LIKE @szBtypeid + '%'
          SELECT  @dTempar = ISNULL(SUM([total]), 0)
          FROM    dlya
          WHERE   [etypeid] = @szEtypeid AND RedOld = 'F'
                  AND [atypeid] = '0000200001'
                  AND [btypeid] LIKE @szBtypeid + '%'
          SELECT  @dTotal = @dTotal - @dTempar
          SELECT  @dTempar = ISNULL(SUM([total]), 0)
          FROM    dlya
          WHERE   [etypeid] = @szEtypeid AND RedOld = 'F'
                  AND [atypeid] = @szAtypeid
                  AND [btypeid] LIKE @szBtypeid + '%'
                  AND [date] > @Enddate
          SELECT  @dTotal = @dTotal - @dTempar
          SELECT  @dTempar = ISNULL(SUM([total]), 0)
          FROM    dlya
          WHERE   [etypeid] = @szEtypeid AND RedOld = 'F'
                  AND [atypeid] = '0000200001'
                  AND [btypeid] LIKE @szBtypeid + '%'
                  AND [date] > @Enddate
          SELECT  @dTotal = ISNULL(@dTotal, 0) + ISNULL(@dTempar, 0)
          SELECT  @dQty = ISNULL(@dTotal, 0)
          RETURN 0

        END      
      ELSE 
        IF @szSelect = 'send' 
          BEGIN
            SELECT  @dTotal = ISNULL(SUM(tax_total), 0)
            FROM    DlyData
            WHERE   btypeid = @szBtypeid AND RedOld = 'F'
                    AND vchtype IN (23, 29)
                    AND pdetail <> 2
            SELECT  @dQty = ISNULL(SUM(TOTAL), 0)
            FROM    dlya
            WHERE   btypeid = @szBtypeid AND RedOld = 'F'
                    AND vchtype = 24
                    AND (atypeid LIKE '0000100003%'
                         OR atypeid LIKE '0000100004%')
            SELECT  @dTotal = -1 * @dTotal - @dQty
            SELECT  @dQty = ISNULL(SUM(taxtotal), 0)
            FROM    inicommission
            WHERE   btypeid = @szBtypeid
                    AND type = 4 
            SELECT  @dTotal = @dTotal + @dQty
            SELECT  @dQty = ISNULL(SUM(tax_total), 0)
            FROM    DlyData
            WHERE   btypeid = @szBtypeid AND RedOld = 'F'
                    AND vchtype = 52
            SELECT  @dTotal = ISNULL(@dTotal, 0) + ISNULL(@dQty, 0)
            SELECT  @dQty = ISNULL(@dTotal, 0)
          END
        ELSE 
          IF @szSelect = 'commission'  --委托发货
            BEGIN
              SELECT  @dQty = ISNULL(SUM(Tax_total), 0)
              FROM    DlyData
              WHERE   btypeid LIKE @szBtypeid + '%' AND RedOld = 'F'
                      AND vchtype IN (30, 25, 50)
                      AND pdetail = 2
                      AND [date] <= @EndDate  
				--结算
              SELECT  @dTotal = ISNULL(SUM(Tax_total), 0)
              FROM    DlyData
              WHERE   btypeid LIKE @szBtypeid + '%' AND RedOld = 'F'
                      AND vchtype = 26
                      AND [date] <= @enddate    
              SELECT  @dTotal = @dQty + @dTotal
				--期初
              SELECT  @dQty = ISNULL(SUM(total), 0)
              FROM    iniCommission
              WHERE   btypeid LIKE @szBtypeid + '%'
                      AND type = 1
              SELECT  @dTotal = ISNULL(@dQty, 0) + ISNULL(@dTotal, 0)
              SELECT  @dQty = ISNULL(@dTotal, 0)
            END
          ELSE 
            IF @szSelect = 'recommission' --受托结算
              BEGIN                
                SELECT  @dQty = ISNULL(SUM(Tax_total), 0)
                FROM    DlyData
                WHERE   btypeid LIKE @szBtypeid + '%' AND RedOld = 'F'
                        AND vchtype IN (31, 27, 51)
                        AND pdetail = 2
                        AND [date] <= @EndDate  

					--结算
                SELECT  @dTotal = ISNULL(SUM(Tax_total), 0)
                FROM    DlyData
                WHERE   btypeid LIKE @szBtypeid + '%' AND RedOld = 'F'
                        AND vchtype = 28
                        AND [date] <= @enddate    
                SELECT  @dTotal = @dQty + @dTotal
					--期初
                SELECT  @dQty = ISNULL(SUM(Taxtotal), 0)
                FROM    iniCommission
                WHERE   btypeid LIKE @szBtypeid + '%'
                        AND type = 5
                SELECT  @dTotal = ISNULL(@dQty, 0) + ISNULL(@dTotal, 0)
                SELECT  @dQty = ISNULL(@dTotal, 0)
              END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
/******************************************20130702********************************************/
/*

1、加盟商不启用配货流程，两个帐要一致；
2、加盟商基本信息中，增加默认付款账户，在加盟商基本信息分支机构页，增加一个默认账户付款账户（新增时不显示，且默认为已启用流程，修改时才显示出来）
*/

-- Branch 加 PayAtypeId，不启用配货流程时默认付款科目
IF NOT EXISTS(select * from dbo.syscolumns where id = object_id(N'[dbo].[Branch]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name = 'PayAtypeId')
BEGIN
	ALTER TABLE dbo.Branch ADD
	PayAtypeId VARCHAR(50) NOT NULL CONSTRAINT DF_Branch_PayAtypeId DEFAULT ''
END
GO
-----------------------------罗靖修改于2011-08-22日，增加往来单位换货率查询的修改
-----------------------------罗靖修改于2011-08-22日，增加加盟机构换货率查询的修改

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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


--  ********************************************************************************************        
--  ||                                                                                                
--  ||   FZGetBaseInfo                                                        
--  ||   过程功能：得到某一基本信息的记录        
--  ||=========================================================================================        
--  ||   参数说明：  参数名称         类型            意义                     输入输出        
--  ||            -----------------------------------------------------------------------------        
--  ||            @cMode  char(5)  :基本信息类型参数   IN        
--  ||            @szTypeid  varchar(50) :根节点Typeid   IN        
--  ||=========================================================================================           
/*    
在查询EType时，增加ECustom1,ECustom2,ECustom3,ECustom4,ECustom5     
在查询atype时，增加ACustom1,ACustom2,ACustom3,ACustom4,ACustom5，  
在查询btype时，增加BCustom1,BCustom2,BCustom3,BCustom4,BCustom5，以满足FZCS需要    
在查询ptype时，增加查询PCustom1,PCustom2,PCustom3,PCustom4,PCustom5，以满足FZCS的需要    
2011-6-24 9:33:57 黄文武    
*/    
-- 2010-09-10  cqhua   #1      
-- 加配货价，配货折扣      
/*
	--作者:QF
	--时间:2011-09-01
	--描述:修改CS往来单位、加盟机构换货率查询,以便满足BS的查询
*/
CREATE    PROCEDURE FZGetBaseInfo
(
 @cMode varchar(5),
 @szTypeid varchar(50)
)
AS 
IF (@szTypeId = ''   OR @szTypeId = '00000') 
  SET @szTypeId = '%'       
--ELSE SET @szTypeId = @szTypeId + '%'        
IF @cMode = 'E' AND @szTypeId = '%'       --BS 超级用户给VIP充值生成凭证。经手人为超级用户，导致查不出来
	SET @szTypeId ='00000'
	
IF @cMode = 'A' 
  SELECT  TYPEID,
          PARID,
          SONNUM,
          USERCODE,
          FULLNAME,
          [NAME],
          NAMEPY,
          COMMENT,
          BranchID,
          ACustom1,
          ACustom2,
          ACustom3,
          ACustom4,
          ACustom5
  FROM    ATYPE
  WHERE   TYPEID = @szTypeid
          AND DELETED = 0
  ORDER BY TYPEID        
IF @cMode = 'B' 
  begin        
    SELECT  B.TYPEID,
            B.PARID,
            B.SONNUM,
            B.USERCODE,
            B.FULLNAME,
            B.[NAME],
            B.NAMEPY,
            B.COMMENT,
            address,
            B.TEL1,
            b.tel2,
            b.netAddress,
            b.email,
            B.POSTCODE,
            B.PERSON,
            B.TAXno,
            B.FAXno,
            B.BANK,
            b.ACcOUNT,
            ISNULL(b.FULLNAME, '') AS RFULLNAME,
            SUM(ISNULL(d.ArTotal00, 0)) as ArTotal00,
            SUM(ISNULL(d.ApTotal00, 0)) as ApTotal00,
            ARWARNUP,
            APWARNUP,
            b.inichange,
            b.canchange,
            b.CheckAndAccept,
            BarterRate,
            BarterTerm,
            isnull(c.PriceTypeid, '') as PriceTypeid,
            isnull(c.MarketDiscountID, '') as MarketDiscountID,
            isnull(DiscountTypeid, '') as DiscountTypeid,
            LowLimitation,
            TaxRate,
            B.BranchID,
						ISNULL(X.OpID,0) AS OPID,
						ISNULL(X.Days,0) AS DAYS,
						ISNULL(X.InRate,0) AS INRATE,
						ISNULL(X.OutRate,0) AS OUTRATE,
						ISNULL(X.MaxDays,0) AS MAXDAYS,
            BCustom1,
            BCustom2,
            BCustom3,
            BCustom4,
            BCustom5,
            B.[stop],
			case when X.OpID is null then 0 else 1 end as rateflag,
			personb,personc,telb,telc,wuliu
    FROM    BTYPE B
		LEFT JOIN ChangeGoodsSetting X
		ON     B.TYPEID = X.BTYPEID AND EXISTS(SELECT SubValue FROM sysdata WHERE SubName = 'ProcTypeName' AND Subvalue='FZCS')
    LEFT JOIN BtypeDistribute c
    on      b.typeid = c.Btypeid
    LEFT JOIN (select btypeid,
                      SUM(ISNULL(ArTotal00, 0)) as ArTotal00,
                      SUM(ISNULL(ApTotal00, 0)) as ApTotal00
               FROM   BranchBtype
               group by btypeid) d
    on      b.typeid = d.btypeid
    WHERE   B.TYPEID = @szTypeid
            AND B.DELETED = 0
    GROUP BY B.TYPEID,
            B.PARID,
            B.SONNUM,
            B.USERCODE,
            B.FULLNAME,
            B.[NAME],
            B.NAMEPY,
            B.COMMENT,
            address,
            B.TEL1,
            b.tel2,
            b.netAddress,
            b.email,
            B.POSTCODE,
            B.PERSON,
            B.TAXno,
            B.FAXno,
            B.BANK,
            b.ACcOUNT,
            b.FULLNAME,
            d.ArTotal00,
            d.ApTotal00,
            ARWARNUP,
            APWARNUP,
            b.inichange,
            b.canchange,
            b.CheckAndAccept,
            BarterRate,
            BarterTerm,
            c.PriceTypeid,
            c.MarketDiscountID,
            DiscountTypeid,
            LowLimitation,
            TaxRate,
            B.BranchID,
            BCustom1,
            BCustom2,
            BCustom3,
            BCustom4,
            BCustom5,
            B.[stop],
						X.OpID,
						X.Days,
						X.InRate,
						X.OutRate,
						X.MaxDays,personb,personc,telb,telc,wuliu
    ORDER BY B.TYPEID        
  end        
IF @cMode = 'BC' 
  begin        
    declare @BranchType int   
    IF @szTypeid = '%'
      OR @szTypeid = '' 
      SET @szTypeid = '00000'
    select  @BranchType = BranchType
    FROM    Branch
    where   BranchID = @szTypeid       
  -- #1 去掉多余字段      
    IF @BranchType <> 4 
      SELECT  B.BranchID AS Typeid,
              B.PARID,
              B.SONNUM,
              B.USERCODE,
              B.FULLNAME,
              B.[NAME],
              B.NAMEPY,
              B.COMMENT,
              address,
              DefTaxRate,
              DefBtypeId,
              DefKtypeId,
              DefAtypeId,
              CashAsBillMoney,
              RoundType,
              PayType,
              B.TEL,
              b.email,
              b.btypeid,
              BranchType,
              e.typename,
              b.selfhelp,
              b.selfiniyear,
              b.iniover,
              isnull(c.PriceTypeid, '') as PriceTypeid, -- 零售价      
              isnull(c.DiscountTypeid, '') as DiscountTypeid,-- 零售折扣      
              isnull(f.PriceTypeid, '') as PriceTypeid1, -- 配货价      
              isnull(f.DiscountTypeid, '') as DiscountTypeid1,-- 配货折扣      
              b.checkandaccept,
              b.payatypeid,
              a.FullName AS afullname,
              BCCustom1,
              BCCustom2,
              BCCustom3,
              BCCustom4,
              BCCustom5,
							DefCashId,
							0 as rateflag
      FROM    Branch B
      LEFT JOIN BtypeDistribute c
      on      b.branchid = c.branchid
              and c.type = 0
      LEFT JOIN BranchType e
      on      b.BranchType = e.typeid
      LEFT JOIN BtypeDistribute f
      on      b.branchid = f.branchid
              and f.type = 4
      LEFT JOIN dbo.Atype a ON b.PayATypeId = a.TypeID AND b.BranchID = a.BranchID
      WHERE   B.BranchID = @szTypeid
              AND B.DELETED = 0
      ORDER BY B.BranchID        
    ELSE   -- 加盟机构      
      SELECT  B.BranchID AS Typeid,
              B.PARID,
              B.SONNUM,
              B.USERCODE,
              B.FULLNAME,
              B.[NAME],
              B.NAMEPY,
              B.COMMENT,
              b.address,
              DefTaxRate,
              DefBtypeId,
              DefKtypeId,
              DefAtypeId,
              CashAsBillMoney,
              RoundType,
              PayType,
              B.TEL,
              b.email,
              b.btypeid,
              BranchType,
              e.typename,
              b.selfhelp,
              b.selfiniyear,
              b.iniover,
              d.ARWARNUP,
              d.BarterRate,
              d.BarterTerm,
              d.IniChange,
              d.CanChange,
              ISNULL(f.PriceTypeid, '') AS JoinPriceTypeid,
              ISNULL(f.DiscountTypeid, '') AS JoinDiscountTypeid,
              
              isnull(c.PriceTypeid, '') as PriceTypeid, -- 零售价      
              isnull(c.DiscountTypeid, '') as DiscountTypeid,-- 零售折扣  
                      
              isnull(f.PriceTypeid, '') as PriceTypeid1, -- 配货价      
              isnull(f.DiscountTypeid, '') as DiscountTypeid1,-- 配货折扣                
              b.checkandaccept,
              b.payatypeid,
              a.FullName AS afullname,
              BCCustom1,
              BCCustom2,
              BCCustom3,
              BCCustom4,
              BCCustom5,
							ISNULL(X.OpID,0) AS OPID,
							ISNULL(X.Days,0) AS DAYS,
							ISNULL(X.InRate,0) AS INRATE,
							ISNULL(X.OutRate,0) AS OUTRATE,
							ISNULL(X.MaxDays,0) AS MAXDAYS,
							DefCashId,
							case when X.OpID is null then 0 else 1 end as rateflag
      FROM    Branch B
      inner join btype d
      on      d.typeid = b.btypeid
			LEFT JOIN ChangeGoodsSetting x
			ON      D.TYPEID = X.BTYPEID	 AND EXISTS(SELECT SubValue FROM sysdata WHERE SubName = 'ProcTypeName' AND Subvalue='FZCS') 		
      LEFT JOIN BtypeDistribute c
      on      b.branchid = c.branchid
              and c.type = 0
      LEFT JOIN BranchType e
      on      b.BranchType = e.typeid
      LEFT JOIN BtypeDistribute f
      on      b.branchid = f.branchid
              and f.type = 4
      LEFT JOIN dbo.Atype a ON b.PayATypeId = a.TypeID AND b.BranchID = a.BranchID
      WHERE   B.BranchID = @szTypeid
              AND B.DELETED = 0
      ORDER BY B.BranchID        
  -- #1      
  end        
IF @cMode = 'D' 
  begin        
    SELECT  Typeid as Dtypeid,
            TYPEID,
            PARID,
            USERCODE,
            FULLNAME,
            NAMEPY,
            COMMENT,
            BranchID,
            DCustom1,
            DCustom2,
            DCustom3,
            DCustom4,
            DCustom5
    FROM    DEPARTMENT
    WHERE   TYPEID like @szTypeid
            and DELETED = 0
            and typeid <> '00000'
    ORDER BY TYPEID        
  end        
IF @cMode = 'E' 
  begin        
    SELECT  E.TYPEID,
            E.PARID,
            E.USERCODE,
            E.FULLNAME,
            E.[NAME],
            E.NAMEPY,
            E.SonNum,
            E.COMMENT,
            E.Dtypeid,
            ISNULL(D.FULLNAME, '') AS EDEPT,
            E.TEL,
            E.ADDRESS,
            E.ZkPopedom,
            E.YHPopedom,
            E.isShopSale,
            E.BranchId,
            E.branchid as bctypeid,
            ECustom1,
            ECustom2,
            ECustom3,
            ECustom4,
            ECustom5,
            E.[stop]
    FROM    EMPLOYEE E
    LEFT OUTER JOIN DEPARTMENT D
    ON      E.Dtypeid = D.TYPEID
    WHERE   E.TYPEID = @szTypeid
            AND E.DELETED = 0
    ORDER BY E.TYPEID   
    
  end        
IF @cMode = 'K' 
  begin        
    SELECT  TYPEID,
            PARID,
            SONNUM,
            USERCODE,
            FULLNAME,
            [NAME],
            NAMEPY,
            COMMENT,
            branchid as bctypeid,
            KCustom1,
            KCustom2,
            KCustom3,
            KCustom4,
            KCustom5,
            IsDefault,
            (Select CheckAndAccept
             From   Btype
             where  Typeid = Stock.Typeid
                    and left(typeid, 5) in ('00007', '00003')) as CheckAndAccept
    FROM    STOCK
    WHERE   TYPEID = @szTypeid
            AND DELETED = 0
            AND substring(Typeid, 1, 5) not in ('99999')
    ORDER BY TYPEID        
  end        
IF @cMode = 'P' 
  begin        
    SELECT  p.TYPEID,
            p.PARID,
            p.SONNUM,
            p.USERCODE,
            p.FULLNAME,
            p.[NAME],
            p.NAMEPY,
            p.COMMENT,
            p.STANDARD,
            p.TYPE,
            p.AREA,
            UNIT1,
            UNIT2,
            SingleUnit,
            MininumPrice AS minprice,
            UNITRATE1,
            BuyUnit,
            SaleUnit,
            PhUnit,
            GoodsUnit,
            COSTMODE,
            BARCODE,
            BREAKWARN,
            Stop,
            CONVERT(NUMERIC(24,2),retailPrice) AS retailPrice,
            FORMATID,
            CSPZ,
            trade,
            stopdate,
            IssueDate,
            btypeid1 AS btypeid,
			changerule,
            PCustom1,
            PCustom2,
            PCustom3,
            PCustom4,
            PCustom5,
			sizegroupid,
			case when sizegroupid=1 then '' else isnull((select top 1 [name]  from sizegroup where sizegroupid =p.sizegroupid),'')  end as pstypeid_psfullname
    FROM    PTYPE p
    WHERE   TYPEID = @szTypeid
            AND DELETED = 0 /*AND SONNUM = 0*/
    ORDER BY typeid        
  end        
/*IF @cMode = 'R' SELECT TYPEID, PARID, SONNUM, USERCODE, FULLNAME, [NAME], NAMEPY, COMMENT         
    FROM AREATYPE         
   WHERE TYPEID LIKE @szTypeid AND DELETED = 0 AND SONNUM = 0 ORDER BY TYPEID        
IF @cMode = 'Z' SELECT TYPEID, PARID, SONNUM, USERCODE, FULLNAME, [NAME], NAMEPY, COMMENT         
    FROM ZEROTYPE         
   WHERE TYPEID LIKE @szTypeid AND DELETED = 0 AND SONNUM = 0 ORDER BY TYPEID        
*/        
IF @cMode = 'Z' 
  begin        
    Select  AreaID,
            FullName,
            UserCode,
            PinyinCode,
            ParID
    From    Area
    where   AreaID <> '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].[FzUpdateBranch]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FzUpdateBranch]
GO











--  ********************************************************************************************                                    
--  ||                                                                                                                              
--  ||   过程名称： FzUpdateBranch                                                                                                     
--  ||   过程功能：修改基本信息--往来单位                                                                                           
--  ||=========================================================================================                                     
--  ||   参数说明：  参数名称         类型            意义                     输入输出                                             
--  ||            -----------------------------------------------------------------------------                                     
--  ||  	@typeid	 	varchar(50),                    父编号                                                              
--  ||  	@FullName	varchar(100),			全名                                                                
--  ||  	@UserCode	varchar(30),			编码                                                                
--  ||  	@Comment	varchar(50),			备注                                                                
--  ||  	@NamePy 	varchar(100)			拼音码                                                              
--  ||  	@Address           varchar(50)                  地址                                                                
--  ||  	@Tel1 		varchar(100),                   电话1                                                               
--  ||          @Tel2	             varchar(100),              电话2                                                               
--  ||  	@FaxNo	varchar(30),                            传真                                                                
--  ||  	@PostCode 	varchar(10),                    邮编                                                                
--  ||  	@Person 	varchar(20),                    联系人                                                              
--  ||  	@Bank		varchar(50),--                  银行                                                                
--  ||  	@Account	varchar(50),--                  帐户                                                                
--  ||  	@BarterRate      numeric(24,10),--              换货率                                                              
--  ||  	@BarterTerm      int,--                         换货期限                                                            
--  ||  	@discount          numeric(24,10),--            折扣                                                                
--  ||  	@CanChang       bit,--                          补货后是否允许换货                                                  
--  ||  	@IniChang         numeric(24,10),--             期初可换货额                                                        
--  ||  	@creditMoney    numeric(24,10),--               信用额度                                                            
--  ||  	@TaxNo 	varchar(20),--                          税号                                                                
--  ||  	@Comment 	varchar(256)                    备注                                                                
--  ||          @PriceChosse       bit                          售价选择                                                            
--  ||          @LimitBrow            numeric(18, 4)            保底额                                                              
--  ||          @MarketDiscount   numeric(18, 4)                商场扣率                                                            
--  ||          @CheckAndAccept bit                             是否启用验收流程                                                    
--  ||=========================================================================================                                     
CREATE     PROCEDURE FzUpdateBranch
    (
      @typeId VARCHAR(50),
      @FullName VARCHAR(100),       --全名
      @UserCode VARCHAR(30),        --用户编码
      @Name VARCHAR(30),        --简名
      @NamePy VARCHAR(100),       --全名拼音      
      @Address VARCHAR(50),        --地址
      @Tel VARCHAR(50),        --电话1   
      @Email VARCHAR(50),        --Email地址
      @BarterRate NUMERIC(24, 10),     -- 换货率
      @BarterTerm INT,                -- 换货期限
      @usertype INT,                --用户类型0：系统分类不允许修改，1:供应商，2:一般客户，3：商场专柜，4:加盟店，5：代理商，00006加盟店客户，00007：自营店。00007：1#自营店
      @CanChang BIT,                -- 补货后是否允许换货
      @IniChang NUMERIC(24, 10),     --  期初可换货额
      @Comment VARCHAR(256),
      @Btypeid VARCHAR(50),
      @ArUp NUMERIC(24, 10),	  --应收款上限
      @PriceTypeid VARCHAR(15) = '',
      @discountTypeid VARCHAR(15) = '',
      @PriceTypeid1 VARCHAR(15) = '',
      @discountTypeid1 VARCHAR(15) = '',
      @MarketDiscountTypeID VARCHAR(15) = '',
      @CheckAndAccept BIT,
      @PayAtypeId VARCHAR(50), --付款科目
      @DefBtypeid VARCHAR(50) = '',
      @DefKtypeid VARCHAR(50) = '',
      @DefAtypeid VARCHAR(50) = '',
      @DefTaxRate NUMERIC(24, 10) = 0,
      @DefCashAsBillMoney INT = 0,
      @DefRoundType INT = 0,
      @DefPayType INT = -1,
		  @OpID int = 0,
		  @Days int = 0,	--换货周期（间隔天数）
		  @InRate float = 100,	--周期内换货率
		  @OutRate float = 100,	--周期外换货率
		  @MaxDays int = 0,	--最长可换货天数
			@DefCashId varchar(50) = '',
			@rateflag int = 0,
      @Custom1 VARCHAR(255)='',
      @Custom2 VARCHAR(255)='',
      @Custom3 VARCHAR(255)='',
      @Custom4 VARCHAR(255)='',
      @Custom5 VARCHAR(255)=''
    )
AS 
    DECLARE @dbname VARCHAR(30)                                                                                                 
    DECLARE @checkValue INT                                                                                                                   
    DECLARE @Branchid VARCHAR(50)	
    DECLARE @UpdateTag INT			--5：代理商,6:加盟店客户，7：自营店      
    DECLARE @iret INT
    DECLARE @Iflag INT


    IF LEFT(@typeId, 5) = '00006' 
        SET @Branchid = '00004'
    ELSE 
        SET @Branchid = '00001'

    SET nocount OFF        


		--机构由启用验收到不启用验收时：只要有同价/变价配货单/加盟配货/加盟退货未验收及差额调整，不能修改
    IF @CheckAndAccept = 0
        AND EXISTS ( SELECT 1
                     FROM   branch
                     WHERE  CheckAndAccept = 1
                            AND branchid = @typeId ) 
        BEGIN
            IF EXISTS ( SELECT  *
                        FROM    dlyndx
                        WHERE   branchid = @typeId
                                AND vchtype IN ( 212, 218, 232, 224 )
                                AND draft IN ( 4, 6 ) ) 
                RETURN -30--还有单据没有验收
            IF EXISTS ( SELECT  *
                        FROM    dlyndx
                        WHERE   branchid = @typeId
                                AND draft = 1
                                AND vchtype = 230 ) 
                RETURN -31  --配货差额调整单
        END

                                                                                                    
    SELECT  @dbname = 'Branch'                                                                                                   
    EXEC @checkValue= FzCheckBasicSet                                                                                     
    IF @checkValue = 1 -- 查找编号和全名不能完全相同                                                                              
        BEGIN                                                                                                                     
            IF EXISTS ( SELECT  [usercode]
                        FROM    Branch
                        WHERE   [BranchId] <> @typeid
                                AND [fullname] = @fullname
                                AND [usercode] = @usercode
                                AND [deleted] <> 1 ) 
                GOTO error105                                                                
        END                                                                                                                         
    IF @checkValue = 2 --全名不能完全相同                                                                                         
        BEGIN                                                                                                                   
            IF EXISTS ( SELECT  [usercode]
                        FROM    Branch
                        WHERE   [BranchId] <> @typeid
                                AND [fullname] = @fullname
                                AND [deleted] <> 1 ) 
                GOTO error105                                                                
        END                                                                                                                         
    IF @checkValue = 3 --编号不能完全相同                                                                                         
        BEGIN                                                                                                               
            IF EXISTS ( SELECT  [usercode]
                        FROM    Branch
                        WHERE   [BranchId] <> @typeid
                                AND [usercode] = @usercode
                                AND [deleted] <> 1 ) 
                GOTO error105                                                                
        END                                                                                                                         
    IF @checkValue = 4 -- 查找编号和全名都不能完全相同                                                                            
        BEGIN                                                                                                      
            IF EXISTS ( SELECT  [usercode]
                        FROM    Branch
                        WHERE   [BranchId] <> @typeid
                                AND ( [fullname] = @fullname
                                      OR [usercode] = @usercode
                                    )
                                AND [deleted] <> 1 ) 
                GOTO error105                                                                
        END                                                                                                                                                                                                           
               
                                                                                                        
    BEGIN TRAN UPdateB 

    IF LEFT(@typeId, 5) = '00004' 
        SELECT  @Btypeid = btypeid
        FROM    branch
        WHERE   branchid = @typeId  

    IF exists (select 1 from Branch WHERE branchid = @typeId and Branchtype = 7)
        SELECT  @Btypeid = btypeid
        FROM    branch
        WHERE   branchid = @typeId  


    EXEC [dbo].[XW_GetUpdateTag] 'Branch', @UpdateTag OUTPUT
                                            
    UPDATE  [dbo].[Branch]
    SET     [usercode] = @usercode,
            [FullName] = @FullName,
            [Name] = @Name,
            [Address] = @Address,
            [Tel] = @Tel,
            [Email] = @Email,
            [Comment] = @Comment,
            [namepy] = @namepy,
            [Btypeid] = @Btypeid,
            defbtypeid = @DefBtypeid,
            defktypeid = @DefKtypeid,
            defatypeid = @DefAtypeid,
            deftaxrate = @DefTaxRate,
            CashAsBillMoney = @DefCashAsBillMoney,
            RoundType = @DefRoundType,
            PayType = @DefPayType,
            updatetag = @updatetag,
            CheckAndAccept = @CheckAndAccept,
            PayAtypeId = @PayAtypeId,
						DefCashId = @DefCashId,
            BCCustom1 = @Custom1,
            BCCustom2 = @Custom2,
            BCCustom3 = @Custom3,
            BCCustom4 = @Custom4,
            BCCustom5 = @Custom5
    WHERE   [BranchId] = @typeId                                                                           
    IF @@ROWCOUNT = 0 
        GOTO error106  

    SELECT  @usertype = branchtype
    FROM    branch
    WHERE   branchid = @typeId
	
    IF @usertype = 4 
        BEGIN      
            EXEC @iret = FzUpdateB @btypeid, @FullName, @UserCode, @Name,
                @NamePy, @Address, @Tel, '', '', @Email, '', '', '', '', '',
                @BarterRate, @BarterTerm, 0, @CanChang, @IniChang, '', 0,
                @ArUp, @Comment, 0, 0, 0, 0, 0, 0, '', '', '', '', 17, @typeId,@OpID,@Days,@InRate,@OutRate,@MaxDays,@rateflag
            IF @iret <> 0 
                BEGIN 
                    ROLLBACK TRAN UPdateB 
                    RETURN @iret 
                END  
         	/* EXEC [dbo].[XW_GetUpdateTag] 'btype', @UpdateTag OUTPUT
		 Update [dbo].[Btype]                                                                               
		 Set    [usercode]       = @usercode, 
		        [FullName]       = @FullName,                                            
			[Name]           = @Name, 
			[Address]        = @Address,	                                                    
			[Tel1]           = @Tel, 
			[Email]          = @Email,                                                       
			[BarterRate]     = @BarterRate,
			[BarterTerm]     = @BarterTerm,                                                                                                           
			[CanChange]       = @CanChang,
			[IniChange]       = @IniChang,                                                  
			[Comment]        = @Comment,                                                                       
			[namepy]         = @namepy,                                                                                
			[ARWarnUp]       = @ArUp,
                        updatetag = @updatetag                             
		Where  [typeId] = @typeId                                                                           
		if @@ROWCOUNT = 0 goto error106  	                                                           
		if not exists(Select * from dlyndx where Btypeid=@typeid )                                          
		Begin                                                                                               
			UPdate Btype set 
			              nowchange=@IniChang  
			where   [typeId] = @typeId                              
		        if @@ROWCOUNT = 0 goto error106                                                             
		End 
		
		 */



                                
        END 
		-- 更新代销机构时，要同时更新POS登记处的代销单位，两者一一对应 cqh 2011-12-01
		IF @usertype =3
			update dbo.tpx_PosInfo set btypeid=@btypeid where JtypeId = @typeId 

    IF @usertype = 7 and (not exists(select subvalue from sysdata where subvalue = 'GJPFZ91' and subname = 'DBVersion'))
        BEGIN      
            EXEC @iret = FzUpdateB @btypeid, @FullName, @UserCode, @Name,
                @NamePy, @Address, @Tel, '', '', @Email, '', '', '', '', '',
                @BarterRate, @BarterTerm, 0, @CanChang, @IniChang, '', 0,
                @ArUp, @Comment, 0, 0, 0, 0, 0, 0, '', '', '', '', 17, @typeId
            IF @iret <> 0 
                BEGIN 
                    ROLLBACK TRAN UPdateB 
										select @iret
                    RETURN @iret 
                END  
        END
    IF @usertype IN ( 1, 3, 4, 7 ) 
        BEGIN  
		
-- BtypeDistribute 表增加 Type 字段
		-- 0 机构零售单（所有机构包括加盟零售单处用到），此时BtypeID为空，BranchID代表相应机构
		-- 1 供应商预设采购价,本系统只允许本部机构做采购单,机构ID为空
		-- 2 客户（包括加盟商客户）预设售价，机构ID为空
		-- 3 代销单位预设抽成及税率，机构ID为空
		-- 4 机构配货价（收货方），此时BtypeID为空，BranchID代表相应机构
		
  		-- 机构只涉及0，4两种价格
				Declare @TempBtypeId varchar(50)	
            IF @usertype = 4 
                SET @iflag = 0
            ELSE 
                SET @iflag = 1
				if @usertype = 4 
					select @TempBtypeId = btypeid from branch where branchid = @typeid
				else 
					set @TempBtypeId = ''
		-- 零售
            IF @PriceTypeid <> ''
                OR @DiscountTypeid <> '' 
                BEGIN
                    IF NOT EXISTS ( SELECT  1
                                    FROM    BtypeDistribute
                                    WHERE   type = 0
                                            AND btypeid = ''
                                            AND branchid = @typeid ) 
                        INSERT  INTO BtypeDistribute
                                (
                                  Branchid,
                                  btypeid,
                                  PriceTypeid,
                                  MarketDiscountID,
                                  DiscountTypeid,
                                  TaxRate,
                                  flag,
                                  type
                                )
                        VALUES  (
                                  @typeid,
                                  '',
                                  @PriceTypeid,
                                  '',
                                  @discountTypeid,
                                  17,
                                  @iFlag,
                                  0
                                )                                                                                           
                    ELSE 
                        UPDATE  BtypeDistribute
                        SET     PriceTypeid = @PriceTypeid,
                                DiscountTypeid = @discountTypeid
                        WHERE   type = 0
                                AND btypeid = ''
                                AND branchid = @typeid
                END
            ELSE 
                DELETE  FROM BtypeDistribute
                WHERE   type = 0
                        AND btypeid = ''
                        AND branchid = @typeid
		-- 配货
            IF @PriceTypeid1 <> ''
                OR @DiscountTypeid1 <> '' 
                BEGIN
                    IF NOT EXISTS ( SELECT  1
                                    FROM    BtypeDistribute
                                    WHERE   type = 4
                                            --AND btypeid = ''
                                            AND branchid = @typeid ) 
                        INSERT  INTO BtypeDistribute
                                (
                                  Branchid,
                                  btypeid,
                                  PriceTypeid,
                                  MarketDiscountID,
                                  DiscountTypeid,
                                  TaxRate,
                                  flag,
                                  type
                                )
                        VALUES  (
                                  @typeid,
                                  @TempBtypeId,
                                  @PriceTypeid1,
                                  '',
                                  @discountTypeid1,
                                  17,
                                  @iFlag,
                                  4
                                )                                                                                           
                    ELSE 
                        UPDATE  BtypeDistribute
                        SET     PriceTypeid = @PriceTypeid1,
                                DiscountTypeid = @discountTypeid1
                        WHERE   type = 4
                                --AND btypeid = ''
                                AND branchid = @typeid
                END
            ELSE 
                DELETE  FROM BtypeDistribute
                WHERE   type = 4
                        --AND btypeid = ''
                        AND branchid = @typeid
            IF @@error <> 0 
                GOTO error106                                                        
        END
    GOTO success    
                                                                                                                    
    success:                                                                                                                            
    COMMIT TRAN UPdateB                                                                                                          
    RETURN 0	                                                                                                                    
    error105:                                                                                                                           
    RETURN -2                -- '该记录的编号或全名与其它记录相同，与你的配置不符！'+char(13)+                                   
				--          '请更改记录或在基本信息设置模块更改配置！'                                              
    error106:                                                                                                                           
    ROLLBACK TRAN UPdateB                                                                                                        
    RETURN -1  		-- 数据库操作失败，请稍后重试！                                                                     
    error00:                                                                                                                            
    RETURN -3
            	  ---往来单位的usertype类型设置不正确                                                               

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZZ_CreateDly]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZZ_CreateDly]
GO

--  *********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：FZZ_CreateDly                                    
--  ||   过程功能：单据过帐  
--  ||=========================================================================================  
--  ||   参数说明：  参数名称         类型            意义                     输入输出  
--  ||            -----------------------------------------------------------------------------  
--  ||            @nVchcode numeric(10, 0),-    -单据索引表中的记录号（过帐时其它参数可以不用录入）  
--  ||            @szptypeido varchar(50) output,  
--  ||         @szbtypeido varchar(50) output,  
--  ||          @szatypeido varchar(50) output,  
--  ||          @szktypeido varchar(50) output  
--  ||          @szGeneralTotal  numeric(24,10)=0 output,   --返回金额目前为vip 的新增积分  
--  ||      @RetTotalSaleMoney numeric(24,10)=0 output, --返回VIP的减少金额  
--  ||      @RetTotalJFJE      numeric(24,10)=0 output, --返回VIP的减少积分金额  
--  ||      @DelDraft          bit=0 --是否删除原始草稿  
--  ||       
--  ||=========================================================================================     
--  ||   返回值：         值                                     说明  
--  ||       ----------------------------------------------------------------------------------------  
--  ||        -2, -4, -202, -204: ('数据库操作失败');  
--  ||        -11: ('系统没有开帐，请先开帐！');  
--  ||        -12: ('在月结存或开帐日期之前！');  
--  ||        -133: ('往来单位[%s]已经被分类或删除，不能过账！'  
--  ||        -132: ('商品[%s-%s]已经被分类或删除，不能过账！'  
--  ||        -135: (仓库[%s]已经被分类或删除，不能过账！'  
--  ||        -134: ('职员已被删除！');  
--  ||        -136: ('部门已被删除！');  
--  ||        -8: ('收付款金额不相等');  
--  ||       -1: ('仓库[%s]的[%s-%s]商品数量不够或批次成本已变，不能过帐！')  
--  ||        -100:('仓库[%s]的[%s-%s]商品出现了负库存，不能过帐！');  
--  ||        -201:('委托库或受托库的[%s-%s]商品总数量或者明细数量不够或批次成本已变，不能过帐！');  
--  ||        -203:('委托库或受托库的[%s-%s]商品总数量为零，不能过帐！');  
--  ||        -918:('所选仓库无[%s-%s]，不能过帐！')  
--  ||        -205: ('委受托仓库的[%s-%s]商品出库金额为零，不能过帐！');  
--  ||        -206: ('当前单据已被过账或删除！不能过帐');  
--  ||        -297 已经补过货，当前往来单位设置补货不允许换货，不能过帐!  
--  ||        -298 不允许换货不能过帐  
--  ||        -299: ('商品[%s-%s]已经被分类或删除，不能过帐！');  
--  ||        -200: ('删除草稿失败！');  
--  ||        -3: ('明细数量为零，不能过帐');  
--  ||        -6: ('仓库已经删除，不能过帐');  
--  ||        -5,-555:('没有成本价或成本金额为零！请录入后重新过帐')  
--  ||       -1414: ('明细数据为空，无法过帐？');  
--  ||        -6000: ('结算数量为零，但结算金额不为零，不能过帐！')  
--  ||        -6001: ('结算金额为零，但结算数量不为零，不能过帐！')  
--  ||        -6002: ('结算金额为零，不能进行调价！过帐失败！')  
--  ||        -1000: ('往来单位不是最末级，不能过帐！')  
--  ||        -1001: ('职员不是最末级，不能过帐！')  
--  ||        -1002: ('部门不是最末级，不能过帐！')  
--  ||        -1003:  ktypeid  ('选择的仓库不是最末级！过帐失败！')  
--  ||        -1004:  ktypeid2 ('选择的仓库不是最末级！过帐失败！')  
--  ||        -1100:  ('选择的订单已经完成！过帐失败！')  
--  ||        -888: ('主单已被删除，不能过帐！')  
--  ||        -700: ('会员卡不存在！')  
--  ||        -701: ('会员卡已被停用！')  
--  ||        -702: ('会员卡已被挂失！')  
--  ||        -703: ('会员卡储值金额不够！')  
--  ||        -704: ('会员卡储值处理失败！')  
--  ||        -2008:('独立帐套的门店不能由总部做单！')  
--  ||        -2009:('独立门店帐套不做总部的单')  
--  ||        -350: ('先进先出法任何一个商品的颜色及尺码的验收数量均不能多于配送数量！')  
--  ||        -512: ('可能[%S]在基本信息中的颜色或尺码已被删除，系统繁忙暂时无法过帐！')  
--  ||        -911: (成本调整单不能调整库存数量为零的商品);  
--  ||        -43:  ( '科目数据更新失败！请检查科目基本资料是否更改。')  
--  ||        -119: ('出入库成本接近于零不能过帐! ');  
--  ||        -916: ('单据已经过帐！不能重复过帐！');  
--  ||        -1112:('系统数据库忙，暂时不能过帐，请稍候重试！')  
--  ||        -287: ('配送原单已被删除！无法验收过帐')  
--  ||        -600 --可用库存为负库存,不能过帐！  
--  ||        -601 --虚拟库存为负库存,不能过帐！  
--  ||        -101 --仓库不是最末级,不能过帐！ 
--  ||==========================================================================================  

/*
作者：cqhua
日期：2011-08-19,2011-08-20调整中
修改原因：其它出入库单过账

*/
--*********************************************************
--modify by 老罗 2012-08-22 处理case 语句中小数收位
--*********************************************************
CREATE   PROCEDURE FZZ_CreateDly
    (
      @nVchcode 							NUMERIC(10, 0),--单据索引表中的记录号  
      @szptypeido 							VARCHAR(8000) OUTPUT,
      @szbtypeido 							VARCHAR(50) OUTPUT,
      @szatypeido 							VARCHAR(50) OUTPUT,
      @szktypeido 							VARCHAR(50) OUTPUT,
      @szGeneralTotal 						NUMERIC(24, 10) = 0 OUTPUT, --返回金额目前为vip 的新增积分  
      @RetTotalSaleMoney 					NUMERIC(24, 10) = 0 OUTPUT, --返回VIP的减少金额  
      @RetTotalJFJE 						NUMERIC(24, 10) = 0 OUTPUT, --返回VIP的减少积分金额  
      @DelDraft 							BIT = 0, --是否删除原始草稿  
      @operatorid 							VARCHAR(50), --当前操作员  
      @CallSelf 							BIT = 0
    )
AS 
    SET nocount ON  
	  
    DECLARE @PDVchCode INT,@OldVchcode INT  
    SET @PDVchCode 	= CONVERT(INT, @szktypeido)  
    SET @OldVchcode = CONVERT(INT, @szktypeido)  
	--会计科目变量  
    DECLARE @GOODS_ID VARCHAR(50), @AR_ID VARCHAR(50),@AP_ID VARCHAR(50),@GOODS_LOSS_ID VARCHAR(50),@GOODS_GET_ID 	VARCHAR(50),
        @TAX_ID VARCHAR(50),@SALE_INCOME_ID VARCHAR(50),@SALE_COST_ID VARCHAR(50),@PRICEALLOT_CHANGE_ID VARCHAR(50),@ALLOT_INCOME_ID VARCHAR(50),
        @BUY_BUYBACK_ID 		VARCHAR(50), @GOODS_GIVE_ID VARCHAR(50),@GOODS_GIVEME_ID VARCHAR(50), @GOODS_PRODUCE_ID VARCHAR(50),
        @FIXED_REDUCE_ID 		VARCHAR(50),@EXPENSE_HAPPEN_ID VARCHAR(50),@LEndOUT_STOCK VARCHAR(50),@BORROWIN_STOCK VARCHAR(50),
        @LEndOUT_GOODS_ID 		VARCHAR(50),@BORROWIN_GOODS_ID 	VARCHAR(50),@COMMISSION_GOODS_ID 	VARCHAR(50), @RECOMMISSION_GOODS_ID  VARCHAR(50),
        @COMMISSION_STOCK_ID 	VARCHAR(50),@RECOMMISSION_STOCK_ID  VARCHAR(50),@PREPERENTIAL_ID 	VARCHAR(50),@WINCASH_ID VARCHAR(50),@InnerSettlement_ID varchar(50),
        @RI_temp 				NUMERIC(24, 10),@xfje NUMERIC(24, 10),@CCTotal NUMERIC(24, 10)  
    SET @CCTotal 				= 0  
    SET @GOODS_ID 				= '0000100001'  
    SET @AR_ID 					= '0000100005'  
    SET @AP_ID 					= '0000200001'  
    SET @GOODS_LOSS_ID 			= '000040000200001'   
    SET @GOODS_GET_ID 			= '000030000200001'--商品报溢收入  
    SET @TAX_ID 				= '0000200004'  
    SET @SALE_INCOME_ID 		= '0000300001'  
    SET @SALE_COST_ID 			= '0000400001'  
    SET @PRICEALLOT_CHANGE_ID 	= '000030000200005'  
    SET @ALLOT_INCOME_ID 		= '000030000200003'  
    SET @BUY_BUYBACK_ID 		= '000030000200004'  
    SET @GOODS_GIVE_ID 			= '000040000200002'--商品赠出  
    SET @GOODS_GIVEME_ID 		= '000030000200002'--商品获赠收入  
    SET @GOODS_PRODUCE_ID 		= '000030000200006'--商品拆装差价  
    SET @FIXED_REDUCE_ID 		= '000040000300002'--固定资产折旧  
    SET @EXPENSE_HAPPEN_ID 		= '0000100007'  
    SET @LEndOUT_STOCK 			= '9999999999'  
    SET @BORROWIN_STOCK 		= '9999999998'  
    SET @LEndOUT_GOODS_ID 		= '0000100006'  
    SET @BORROWIN_GOODS_ID 		= '0000200002'  
    SET @COMMISSION_GOODS_ID 	= '0000100008'  --委托发出商品款  
    SET @RECOMMISSION_GOODS_ID  = '0000200003'  --受托接收商品款  
    SET @COMMISSION_STOCK_ID 	= '9999900002'  
    SET @RECOMMISSION_STOCK_ID  = '9999900003'  
    SET @PREPERENTIAL_ID 		= '000040000300004'--优惠  
    SET @WINCASH_ID 			= '000040000300003'--提成金额  
	SET @InnerSettlement_ID     ='0000100009'--内部结算
    SET @xfje 					= 0  
    DECLARE @tDate 				VARCHAR(10),
        @nCostMode 				SMALLINT,
        @deleted 				INT,
        @JoinCostPrice 			NUMERIC(24, 10),
        @JoinCostTotal 			NUMERIC(24, 10),
        @convert 				NUMERIC(24, 10),
        @VipCardid 				INT,
        @Vipdiscount 			NUMERIC(24, 10),
        @retVip 				INT,
        @Backmoney 				NUMERIC(24, 10),
        @dTotalMoney 			NUMERIC(24, 10),
        @dTotalinMoney 			NUMERIC(24, 10),
        @nVchType 				NUMERIC(4, 0),
        @szAtypeId 				VARCHAR(50),
        @szPtypeId 				VARCHAR(8000),
        @szbTypeId 				VARCHAR(50),
        @szbTypeId2             VARCHAR(50), ---往来核销一级索引添加第二单位
        @szEtypeId 				VARCHAR(50),
        @szKtypeId 				VARCHAR(50),
        @szKtypeId2 			VARCHAR(50),
        @dTotal 				NUMERIC(24, 10),
        @dQty 					NUMERIC(24, 10),
        @Period 				INT,
        @dPrice 				NUMERIC(24, 10),
        @SaleMode 				VARCHAR(30),
        @ddiscount 				NUMERIC(24, 10),
        @ddiscountprice 		NUMERIC(24, 10),
        @ddiscounttotal 		NUMERIC(24, 10),
        @dtax 					NUMERIC(24, 10),
        @dtaxprice 				NUMERIC(24, 10),
        @dtaxtotal 				NUMERIC(24, 10),
        @dtax_total 			NUMERIC(24, 10),
        @dcostprice 			NUMERIC(24, 10),
        @dcosttotal 			NUMERIC(24, 10),
        @MarketDiscount1 		NUMERIC(10, 2),
        @dTempTax_Total 		NUMERIC(24, 10),
        @SaleMoney 				NUMERIC(24, 10),
        @TempSaleMoney 			NUMERIC(24, 10),
        @szmemo 				VARCHAR(60),
        @usedtype 				CHAR(1),
        @jhdate 				VARCHAR(10),
        @xsdate 				VARCHAR(10),
        @dTemptaxtotal 			NUMERIC(24, 10),
        @dtempcosttotal 		NUMERIC(24, 10),
        @redword 				CHAR(1),
        @dTempQty 				NUMERIC(24, 10),
        @dTempTotal 			NUMERIC(24, 10),
        @dtemp 					NUMERIC(24, 10),
        @sonnum 				INT,
        @nRet 					SMALLINT,
        @YSYFTotal 				NUMERIC(24, 10),
        @execsql 				VARCHAR(1000),
        @dTemp1 				NUMERIC(24, 10),
        @dTemp2 				NUMERIC(24, 10),
        @szTemp 				VARCHAR(30),
        @nTemp 					NUMERIC(18, 0),
        @unit 					INT,
        @packcode 				VARCHAR(100),
        @packRate 				NUMERIC(24, 10),
        @packQty 				NUMERIC(24, 10),
        @OrderList 				VARCHAR(2000),
        @CustValue1 			VARCHAR(50),
        @CustValue2 			VARCHAR(50),
        @CustValue3 			VARCHAR(50),
        @CustValue4 			VARCHAR(50),
        @CustValue5 			VARCHAR(50),
        @CustValue6 			VARCHAR(50),
        @RetailPrice 			NUMERIC(24, 10),
        @BillType 				TINYINT,
        @draft1 				INT,
        @number 				VARCHAR(50),
        @SupplyReturn 			INT   
         --价格跟踪和修改预设售价的配置  
    DECLARE @ForeignDlyorder INT, @RowOrder INT,@branchid VARCHAR(50),@nTrackPrice SMALLINT,@nTrackDiscount SMALLINT,@nModiSalePrice SMALLINT,@type INT,@szAutoSummary VARCHAR(60),
        @DeptID VARCHAR(50),@dPreferential NUMERIC(24, 10),@dWinCashTotal NUMERIC(24, 10),@bargainTotal NUMERIC(24, 10),@nDlyOrder INT,@oDlyOrder INT,@retOrder INT,@dqty_j NUMERIC(24, 10),
        @dcosttotal_j NUMERIC(24, 10),@vipsalemoneyTemp NUMERIC(24, 10),@Vipdiscount_new NUMERIC(24, 10),@VipConsumeTotal NUMERIC(24, 10),@VipiniTotal NUMERIC(24, 10),
        @ifSupply BIT, @InputNO2 VARCHAR(50), @InputNO VARCHAR(50), @InputNO3 VARCHAR(50), @InputNo4 VARCHAR(50), @ColorID INT, @MenDataBase VARCHAR(50),@branchid3 varchar(50),
        @ExpandId VARCHAR(50),@branchidT VARCHAR(50),@branchidT2 VARCHAR(50),@branchidT3 VARCHAR(50),--用来保存内部转款单表尾机构
	    @PHID  INT --用于保存单据业务类型 1配货、2退货、3调配 4销售收款、5预收账款、6其他收款 7采购付款、8预付账款、9其他付款
		
 -----------------------------------------------  
    DECLARE @dTotalMoney1 NUMERIC(24, 10),@dTotalMoney2 NUMERIC(24, 10)-- 销售换货时更新客户换货额专用  
 -----------------------------------------------  
    DECLARE @dTotalMoneyCan NUMERIC(24, 10),@ifCan BIT--记录单据累计可换货额专用变量  
 -------------------------------------------------------------------  
 --------------------------------------- 生成换货记录用到的变量----------------------------------------------------BEGIN  
    DECLARE @Nowchange NUMERIC(24, 10),
        @BarterRate NUMERIC(24, 10),
        @AddChang NUMERIC(24, 10),
        @CutChang NUMERIC(24, 10),
        @BarterTerm NUMERIC(24, 10),
        @NowchangeTem NUMERIC(24, 10),
        @LowLimitation NUMERIC(24, 10),
        @MarketDiscount NUMERIC(24, 10),
        @iniChange NUMERIC(24, 10),
        @BarterType INT  
 ------------------------------------------------------------------------------------------------------------------END  
---------------------------小数位数自定义变量-----------------------------------
DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 


 
    SET @dTotalMoneyCan = 0  
    SET @vipsalemoneyTemp = 0  
    SET @VipConsumeTotal = 0  
    SET @dPreferential = 0   
    SET @SupplyReturn = 0  
    DECLARE @account VARCHAR(50)   
  
    DECLARE @OPID INT  -- 业务类型ID

    DECLARE @JHTHCJ NUMERIC(18, 10) --进货退货差价，写入会计科目  
    SET @JHTHCJ = 0  
    DECLARE @ProcType VARCHAR(50)  
    SELECT  @ProcType = subvalue
    FROM    sysdata
    WHERE   subName = 'ProcTypeName'   
  
    IF @procType = 'FZCS' AND @CallSelf = 0 
    	BEGIN TRAN Account  
		
	
    --从索引表中提取信息@szktypeid入货仓库，@szktypeid2出货仓库  
    SELECT TOP 1  @nVchType = VchType,
            @tDate = [Date],
            @szbTypeId = btypeid,
            @szbTypeId2 = btypeid2, --往来核销单据一级明细添加第二单位
            @szEtypeId = etypeid,
            @szKtypeId = ktypeid,
            @szKtypeid2 = ktypeid2,
            @INputno2 = Inputno2,
            @inputno3 = inputno3,
            @inputno4 = inputno4,
            @VipCardid = VipCardID,
            @VipDiscount = VipDiscount,
            @deptid = Dtypeid,
            @INputNo = InputNo,
            @BarterType = BarterType,
            @draft1 = draft,
            @BackMoney = BackMoney,
            @ExpandId = ExpandId,
            @number = number,
            @OrderList = ISNULL(OrderList, ''),
            @BillType = Billtype,
            @branchid = ISNULL(branchid, ''),
            @branchidT = ISNULL(Branchid, ''),
            @branchidT2 = ISNULL(branchid2, ''),
			@branchid3 = ISNULL(branchid3,''),
            @account = account,
			@PHID=PHID
    FROM    dlyndx
    WHERE   Vchcode = @nVchcode  
	IF @draft1 =2 --单据已经过账
	BEGIN
		SET @nRet=-916 
		GOTO error
 	END


    --IF EXISTS ( SELECT  1 FROM    dlyndx WHERE   vchtype = 230 AND vchcode = @nVchcode ) 
  
  
    declare @TempExpandid varchar(20)
    set @TempExpandid = @ExpandId
    SET @ExpandId = '0'  

	
    SELECT TOP 1 @MenDataBase = ISNULL(subvalue, '') FROM    sysdata WHERE   subname = 'MenDataBase'  
   
    DECLARE @szktypeidT VARCHAR(50),
        @szktypeidT2 VARCHAR(50)  
    SET @szktypeidT = @szktypeid  
    SET @szktypeidT2 = @szktypeid2  
  
	--判断机构是否开账 BEGIN
    IF @branchidT2 <> '' 
    BEGIN  
        IF @nVchType IN (222,234,232,224)
        BEGIN  
            IF ( @nVchType IN(222,234)) AND EXISTS ( SELECT TOP 1 1 FROM   branch WHERE  branchid = @branchidT2 AND iniover = 0)  --判断发货方  
            BEGIN  
                SET @nRet = -11  
                GOTO error  
            END    
            IF ( @nVchType IN(232,224)) AND EXISTS ( SELECT TOP 1 1 FROM   branch WHERE   branchid = @branchidT  AND iniover = 0) --判断收货方  
            BEGIN  
                SET @nRet = -13  
                GOTO error  
            END  
        END  
        ELSE 
        BEGIN  
            IF EXISTS ( SELECT TOP 1 1 FROM    branch WHERE   branchid = @branchidT2 AND  iniover = 0) 
            BEGIN  
                SET @nRet = -11  
                GOTO error  
            END  
            IF EXISTS ( SELECT TOP 1 1 FROM    branch WHERE   branchid = @branchidT AND iniover = 0) 
            BEGIN  
                SET @nRet = -13  
                GOTO error  
            END  
        END  
    END  
    ELSE 
    BEGIN  
        IF EXISTS ( SELECT TOP 1 1 FROM    branch WHERE  branchid = @branchidT AND  iniover = 0) 
        BEGIN  
            SET @nRet = -14  
            GOTO error  
        END  
    END  
	--判断机构是否开账END

    --零售相关VIP变量-- 对于销售出库、销售退货、销售换货（一样处理）表头VIP，积分用  
    DECLARE @LSvipCardid VARCHAR(50)  
    SET @LSvipCardid = @vipCardid  
  
	--CQH 2012-02-22 BS 的所有判断都分布在客户端了,其中新增存储过程FZDataCheck_BS检测日期。其它如基本信息，VIP的检测之前客户端都是有的 BEGIN
    IF @procType = 'FZCS'  
	BEGIN
            DECLARE @tmpDraft int
            if @TempExpandid = 'LSJC'
               SET @tmpDraft = 10
            else 
               set @tmpDraft = @draft1
	    EXEC @nRet= FZDataCheck @nVchcode, @tmpDraft, @MenDataBase, @VipCardid,
	        @Period OUTPUT, @szBtypeId, @szEtypeid, @deptid, @szKtypeId,
	        @szKtypeId2, @nVchtype, @VipDiscount, @tDate, @branchidT2, @branchidT  
	    IF @nret < 0 
	        GOTO error  
  	END
	ELSE
		Select @Period = isnull(SubValue,0) from SysData where SubName='Period'   -- 增加会计期间管理


	IF @nVchType =230
    BEGIN  
        IF NOT EXISTS ( SELECT  1 FROM    dlyndx WHERE   vchcode = @oldvchcode ) 
        BEGIN  
            SET @nRet = -916 --单据已经过账  
			GOTO error
        END  
        DECLARE @szptypeidoo VARCHAR(50),@szktypeidoo VARCHAR(50)  
        EXEC @nRet= FZZ_CreateDly_CETZ @nVchcode, @oldvchcode,@szptypeidoo OUTPUT, @szktypeidoo OUTPUT, @operatorid  
        IF @nRet >= 0 
            GOTO Successed  
        ELSE 
        BEGIN  
            SET @szptypeid = @szptypeidoo   
            SET @szbtypeid = @szbtypeido   
            SET @szatypeid = @szatypeido  
            SET @szktypeid = @szktypeidoo   
            GOTO error  
        END  
    END  


    IF @nVchtype IN ( 212, 218 )  -- 变价配货单,同价配货单 过账走单独路线
    BEGIN  
        EXEC @nRet= FZZ_CreateDly_PHNew @nVchcode, @szptypeido OUTPUT,@szbtypeido OUTPUT, @szatypeido OUTPUT, @szktypeido OUTPUT,@DelDraft, @OldVchcode  
        IF @nRet >= 0 
        BEGIN    
            GOTO Successed  
        END  
        ELSE 
        BEGIN  
            SET @szptypeid = @szptypeido   
            SET @szbtypeid = @szbtypeido   
            SET @szatypeid = @szatypeido  
            SET @szktypeid = @szktypeido   
            GOTO error  
        END  
    END  

	--CQH 2012-02-22 BS 的所有判断都分布在客户端了,其中新增存储过程FZDataCheck_BS检测日期。其它如基本信息，VIP的检测之前客户端都是有的 END
    SET @YSYFTotal = 0  
    SELECT  @szAtypeid = ''  
    SELECT  @szPtypeid = ''  
   
  
    DECLARE @TempVchType INT  
    DECLARE @TempBilltype INT  
    DECLARE @nVchcodenew INT  
    SET @nVchcodenew = 0  
    DECLARE @Tempdraft INT  
    SET @Tempdraft = 4  
    DECLARE @TempBtypeID VARCHAR(50)  
    SET @TempBtypeID = ''  
  
    DECLARE @TempEtypeID VARCHAR(50) --验收方经手人默认写任意一个  
    SET @TempEtypeID = ''
    DECLARE @CheckAndAccept INT --机构是否启用验收流程  
    SET @CheckAndAccept = 1  --默认启用  
  
    IF @nVchtype IN ( 222, 234 ) 
    BEGIN  
		DECLARE  @BranchDefAtype VARCHAR(50)=''--取默认机构的收付款科目
        IF @procType = 'FZCS' 
            SELECT  @CheckAndAccept = 0 --服装CS总是不启用加盟店验收流程
        ELSE 
            SELECT  @CheckAndAccept = ISNULL(CheckAndAccept, 0),@BranchDefAtype=PayAtypeId FROM    Branch WHERE   BranchID = @branchidT  

        --SELECT  dlyorder INTO    #bakdlytemp FROM    bakdly WHERE   vchcode = @nvchcode  AND ptypeid <> '' ORDER BY dlyorder  
        DECLARE @dlyordertemp INT,@dlyordertempnew INT 
        SET @dlyordertemp = 0  
        SET @dlyordertempnew = 0  

        IF @nVchType = 222 
        BEGIN  
            SET @TempVchType = 232  
			SET @TempBilltype = 8 
            IF @procType = 'FZCS' 
            BEGIN
			    --SELECT  @TempBtypeID = btypeid FROM    dlyndx WHERE   Vchcode = @nvchcode  
				SET @TempBtypeID =@szbTypeId --没得必要再从单据处取
			END
            ELSE 
                SELECT  @TempBtypeID = Btypeid FROM    Branch WHERE   branchid = @branchidT2  
        END  
        IF @nVchType = 234 
        BEGIN  
            SET @TempVchType = 224  
            SET @TempBilltype = 2  
            IF @procType = 'FZCS' 
			BEGIN
                --SELECT  @TempBtypeID = btypeid FROM    dlyndx WHERE   Vchcode = @nvchcode  
				SET @TempBtypeID =@szbTypeId --没得必要再从单据处取
			END
            ELSE 
                SELECT  @TempBtypeID = btypeid FROM    Branch WHERE   branchid = @branchidT2  
        END  
		--验收方经手人默认写任意一个  
        IF @procType = 'FZCS' 
		BEGIN
            --SELECT  @TempEtypeID = EtypeId  FROM    dlyndx WHERE   Vchcode = @nvchcode  
			SELECT  @TempEtypeID =@szEtypeId --没得必要再从单据处取
		END
        ELSE 
        BEGIN
            IF @nVchType = 222 
                SELECT TOP 1 @TempEtypeID = ISNULL(typeid, '') FROM    employee WHERE    branchid = @branchidT AND sonnum = 0 AND deleted = 0--加盟机构  
            ELSE 
                SELECT TOP 1 @TempEtypeID = ISNULL(typeid, '') FROM    employee WHERE   sonnum = 0 AND deleted = 0 AND LEFT(branchid, 5) <> '00004'  
        END

        IF ( @nVchtype = 222
             OR @nVchtype = 234
           )
            AND @CheckAndAccept = 0   --未启用验收  
            BEGIN  
                SET @Tempdraft = 3 --直接过账  
                IF @TempEtypeID = '' --验收方无经手人，不能直接过账  
                    SET @Tempdraft = 4   
                IF @BranchDefAtype='' RETURN  -25 --未启用验收流程的情况下必须要设置机构的默认收付款科目
            END  


		--加入主索引表 --只有Vchtype不同，加减10,draft =1  @TempBilltype 加盟方为8，总部为2,@TempEtypeID,@tempBtypeid,@nvchcode -记录关联单据ID  
        INSERT  INTO Dlyndx
        (
              BillType,VchType,Draft,Redold,Date,Number,BtypeId,BranchId,BranchId2,EtypeId,KtypeId,KtypeId2,
              IfCheck,Checke,Period,RedWord,Account,InputNo,Qty,Total,InvoiceTag,InvoiceTotal,Dtypeid,VipCardID,
              VipDiscount,BarterType,InputNO1,InputNO2,InputNO3,InputNO4,InputNO5,CheckAndAccept,IfOut,LimitTime,
              DlyVchcode,ZdDiscount,ZdDiscountprice,Preferential,AcceptState,AtypeId,AtypeTotal,ExpandId,BackMoney,
			  IsExported,Flag,YSYFTotal,ForeignVchcode,AccountTime,SiteId,RetailBackFlag,CurrUnDoIntegral,LastUnDoIntegral,
              VerifyFlow,LJYSYFTotal,ForeVIPBalance,OrderList,Summary,SkipFlag,Comment   
        )
        SELECT  @TempBilltype,@TempVchType,@Tempdraft AS Draft,Redold,Date,Number,@tempBtypeid,BranchId,BranchId2,@TempEtypeID,KtypeId,KtypeId2,
                IfCheck,Checke,@Period,RedWord,Account,InputNo,Qty,Total,InvoiceTag,InvoiceTotal,Dtypeid,VipCardID,
				VipDiscount,BarterType,InputNO1,InputNO2,InputNO3,InputNO4,InputNO5,CheckAndAccept,IfOut,LimitTime,
                @nvchcode,ZdDiscount,ZdDiscountprice,Preferential,AcceptState,AtypeId,AtypeTotal,ExpandId,BackMoney,
				IsExported,Flag,YSYFTotal,ForeignVchcode,AccountTime,SiteId,RetailBackFlag,CurrUnDoIntegral,LastUnDoIntegral,
                VerifyFlow,LJYSYFTotal,ForeVIPBalance,OrderList,Summary,SkipFlag,Comment
        FROM    dlyndx
        WHERE   Vchcode = @nvchcode  
        IF @@Rowcount < 0 OR @@error <> 0 
        BEGIN  
            IF @procType = 'FZCS'
                AND @CallSelf = 0 
                ROLLBACK TRAN Account  
            RETURN -29611  
        END  
        SET @nVchcodenew = @@IDENTITY  
		
		 --记录关联单据ID  
        UPDATE  dlyndx SET     dlyvchcode = @nVchcodenew WHERE   vchcode = @nvchcode  
		--现在先保存的都是出库方草稿，因为之前保存的都是ktypeid，而出库方应该是ktypeid2  
		--update bakdly set ktypeid=@szktypeid2 where vchcode=@nvchcode  
		IF @@Rowcount < 0 OR @@error <> 0 
		BEGIN  
		    IF @procType = 'FZCS' AND @CallSelf = 0 
		    	ROLLBACK TRAN Account  
		    RETURN -29611  
		END  
		
	  	-- 去掉游标
        /*DECLARE CreateDlytemp CURSOR
            FOR SELECT  dlyorder
                FROM    #bakdlytemp   
        OPEN CreateDlytemp  
		FETCH NEXT FROM CreateDlytemp INTO @dlyordertemp    
        WHILE @@FETCH_STATUS = 0 --@TempBilltype,@szktypeid(验收方为入库),@nVchcodenew,@TempVchType,@branchidT,@tempBtypeid  
		*/
        BEGIN  
			
            INSERT  INTO bakdly
            (
              BillType,BranchID,AtypeId,PtypeId,CostMode,Qty,ColorId,Discount,
			  VipCardID,VipDiscount,DiscountPrice,CostPrice,TaxPrice,Price,CostTotal,Total,
              TaxTotal,Tax_Total,BargainTotal,DiscountTotal,Tax,[Date],UsedType,Unit,[Convert],
              JoinCostPrice,JoinCostTotal,MarketDiscount,MarketDiscount1,SaleMoney,PackCode,PackRate,PackQty,
              RetailPrice,IfSupply,Comment,RowOrder,SaleMode,CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,
              vchtype, vchcode,btypeid,etypeid,ktypeid,dtypeid,OPID,PHRows,UnitRate,SingleUnit
            )
            SELECT   --加盟配货，如果0单价出库，则作为验收的0成本入库，所以CostMode=4  
                    @TempBilltype,@branchidT,AtypeId,PtypeId,
                    CASE WHEN @nVchType = 222 AND BargainTotal = 0 THEN 4 ELSE CASE WHEN CostMode IN ( 4, 6 )  THEN 4 ELSE 0 END END,Qty,
                    ColorId,Discount,
                    VipCardID,VipDiscount,DiscountPrice,
                    CASE @nvchtype  WHEN 234 THEN costprice ELSE ( case when qty = 0 then 0 else  CAST(BargainTotal / qty AS NUMERIC(24,10)) end ) END,
                    TaxPrice,Price,CASE @nvchtype  WHEN 234 THEN costtotal  ELSE BargainTotal END,Total,
                    TaxTotal,Tax_Total,BargainTotal,DiscountTotal,Tax,[Date],Usedtype,Unit,[Convert],
                    JoinCostPrice,JoinCostTotal,MarketDiscount,MarketDiscount1,SaleMoney,PackCode,PackRate,PackQty,
                    RetailPrice,IfSupply,Comment,RowOrder,SaleMode,CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,
                    @TempVchType,@nVchcodenew,@TempBtypeID,etypeid,@szktypeid,dtypeid,OPID,PHRows,UnitRate,SingleUnit
            FROM    BakDly where vchcode =@nvchcode and (ptypeid<>'' OR @procType = 'FZCS') --CS要复制收款科目
            UNION ALL
            SELECT   --加盟配货，如果0单价出库，则作为验收的0成本入库，所以CostMode=4  
                    @TempBilltype,@branchidT,@BranchDefAtype AtypeId,PtypeId,
                    CASE WHEN @nVchType = 222 AND BargainTotal = 0 THEN 4 ELSE CASE WHEN CostMode IN ( 4, 6 )  THEN 4 ELSE 0 END END,Qty,
                    ColorId,Discount,
                    VipCardID,VipDiscount,DiscountPrice,
                    CASE @nvchtype  WHEN 234 THEN costprice ELSE ( case when qty = 0 then 0 else  CAST(BargainTotal / qty AS NUMERIC(24,10)) end ) END,
                    TaxPrice,Price,CASE @nvchtype  WHEN 234 THEN costtotal  ELSE BargainTotal END,Total,
                    TaxTotal,Tax_Total,BargainTotal,DiscountTotal,Tax,[Date],Usedtype,Unit,[Convert],
                    JoinCostPrice,JoinCostTotal,MarketDiscount,MarketDiscount1,SaleMoney,PackCode,PackRate,PackQty,
                    RetailPrice,IfSupply,Comment,RowOrder,SaleMode,CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,
                    @TempVchType,@nVchcodenew,@TempBtypeID,etypeid,@szktypeid,dtypeid,OPID,PHRows,UnitRate,SingleUnit
            FROM    BakDly where vchcode =@nvchcode AND ptypeid='' AND @procType <> 'FZCS' --BS要复制收款科目的金额但科目用收货机构对应的科目
            --WHERE   dlyorder = @dlyordertemp  
            IF @@Rowcount < 0 OR @@error <> 0 
            BEGIN  
                IF @procType = 'FZCS' AND @CallSelf = 0 
                    ROLLBACK TRAN Account  
                RETURN -29611  
            END  

            --SET @dlyordertempnew = @@IDENTITY  

            INSERT  INTO bakdlydetail
            (
              DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],
			  DiscountTotal,CostTotal,salemoney,JoinCostTotal,PHRows,Vchcode,usedtype 
            )
            SELECT  a.dlyorder,b.SIZEID,b.COLORID,b.QTY,b.Total,b.Taxtotal,b.Tax_total,b.BargainTotal,b.[Convert],
                    b.DiscountTotal,CASE @nvchtype  WHEN 234 THEN b.costtotal  ELSE b.BargainTotal END,
                    b.salemoney,b.JoinCostTotal,b.PHRows,@nVchcodenew,a.usedtype
            FROM    bakdlydetail b,bakdly a  where b.vchcode =@nvchcode and a.vchcode =@nVchcodenew  and a.phrows=b.phrows and a.ptypeid<>''


        	IF @@Rowcount < 0 OR @@error <> 0 
            BEGIN  
                IF @procType = 'FZCS' AND @CallSelf = 0 
                    ROLLBACK TRAN Account  
                RETURN -29611  
            END  
			--UPDATE bakdlydetail FROM bakdlydetail a INNER JOIN select dlyorder,phrows bakdly where vchcode = b on a.dlyorder =b.dlyorder
			--唯一码记录写入  
            INSERT  INTO PtypeUniqueCode(vchcode,ptypeid,colorid,sizeid,uniquecode,Traceprice,TraceDisCount)
            SELECT  @nVchcodenew,ptypeid,colorid,sizeid,uniquecode,Traceprice,TraceDisCount FROM    PtypeUniqueCode WHERE   vchcode = @nvchcode  
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  
        	--FETCH NEXT FROM CreateDlytemp INTO @dlyordertemp  
    	END  
    END  

  
    DECLARE @TempDlyVchCode NUMERIC(10, 0)  
    IF @nVchtype IN( 232,224) --单据验收，把关联单据改了  
    BEGIN  
        IF @szbtypeido <> 'check' --不启用验收流程过账的标志,如果是直接过账，则不用改关联  
        BEGIN  
            SELECT  @TempDlyVchCode = DlyVchCode FROM    DlyNdx WHERE   VchCode = @OldVchcode   
            UPDATE  DlyNdx SET     DlyVchcode = @TempDlyVchCode WHERE   VchCode = @nVchCode  
            UPDATE  DlyNdx SET     DlyVchCode = @nVchCode WHERE   VchCode = @TempDlyVchCode  
			delete from PtypeUniqueCode where vchcode=@OldVchcode --删除老单唯一码
        END  
    END  
	
	IF @nVchtype IN(232,234) AND @CheckAndAccept =1
	BEGIN
		 INSERT INTO dbo.DlyNdxB
            ( Vchcode ,
              metypeid ,
              petypeid ,
              mdate ,
              pdate ,
              retypeid ,
              rdate
            )
        VALUES  ( @nVchCode , -- Vchcode - int
                  '' , -- metypeid - varchar(50)
                  @szEtypeID , -- petypeid - varchar(50)
                  GETDATE() , -- mdate - datetime
                  GETDATE() , -- pdate - datetime
                  '' , -- retypeid - varchar(50)
                  GETDATE()  -- rdate - datetime
                )
	END  	
	/* 
	--有一种情况，先录商品后录VIP卡号，过帐前
	--把VIP的相关信息调出来的，过帐后就看不到“此前积分/此前余额”。
	--需求确认按单据网格中最后一行的“VIP列”显示VIP的相关信息，有就显示，没有就不显示 (vchtype in (12,100)最后把VIP充值的单据dlyndx的cardid清空了）  

 	--零售单主表VIP等于最后一行明细VIP  BEGIN
	*/
	
	IF @nVchType IN (100,12)  
	BEGIN
	   IF EXISTS(SELECT TOP 1 vipcardid FROM   bakdly WHERE  vchcode = @nVchcode  AND vipcardid <> 0 AND ptypeid <> '')
		BEGIN
			SELECT TOP 1 @vipCardid=vipcardid FROM   bakdly WHERE  vchcode = @nVchcode  AND vipcardid <> 0 AND ptypeid <> '' ORDER BY dlyorder DESC
			UPDATE  dlyndx   SET vipcardid = ISNULL(@vipCardid, 0)   WHERE   vchcode = @nVchcode AND vchtype IN ( 12, 100 ) 
			--因为并发死锁问题，此段后移，所以VIP要重新取一下
			SELECT @LSvipCardid=@vipCardid
		END
	END
   --零售单主表VIP等于最后一行明细VIP END

    IF @OldVchcode <> 0  AND @nVchType IN (100,12)
    BEGIN  
        SELECT TOP 1  @account = account,@BackMoney = backmoney FROM    dlyndx WHERE   Vchcode = @OldVchcode  
        IF @account = 'COMMONPOSLSJC' 
        BEGIN  
		   -----------新加的如果POS结存过来的单据与POS单商品不一致则不允许过账Begin
	       IF exists(select 1 from 
	                          (select sum(finallytotal) as atotal from dbo.tpx_SaleIndex where draftvchcode = @OldVchcode 
								AND VtypeId IN('00001')) a,
	                          (select sum(salemoney) as btotal from bakdly b where Vchcode = @nVchcode) b where a.atotal <>b.btotal
			)
	       BEGIN
	         SET @nRet = -603
	         GOTO error
	       END
           ----------新加的如果POS结存过来的单据与POS单商品不一致则不允许过账End
            UPDATE  dlyndx
            SET     account = 'COMMONPOSLSJC',
                    backmoney = @BackMoney
            WHERE   Vchcode = @nVchcode  
    	END
        else if @TempExpandid = 'LSJC'
        begin 
	       IF exists(select 1 from 
	                          (select sum(CASE WHEN vchtypename ='POS小票销售单' then retailsum else -retailsum end) as atotal 
								from posretailbill ls  where  draftbillcode = @OldVchcode) a,
	                          (select sum(salemoney) as btotal from bakdly b where Vchcode = @nVchcode) b where a.atotal <>b.btotal
			)
	       BEGIN
	         SET @nRet = -603
	         GOTO error
	       END 
        end  
    END  

	DECLARE @xfje1 NUMERIC(10, 2),@xfje2 NUMERIC(10, 2)  
    DECLARE @CBTZ_YKCJE NUMERIC(24, 10)--调整前的库存金额  
    DECLARE @CBTZ_XKCJE NUMERIC(24, 10)--调整前的库存金额  
    DECLARE @retailprice1 NUMERIC(24, 10),@RetailTotal NUMERIC(24, 10)  
    DECLARE @temp_j NUMERIC(24, 10)  
    DECLARE @tempJoinCostTotalF NUMERIC(24, 10),@tempCostTotalF NUMERIC(24, 10) --分摊成本金额用  
    
    /*-------FZBS价格跟踪从系统配置移植到各个类型单据的业务配置下，且原折扣和价格跟踪合并成现在的统一一个价格跟踪设置---*/
    --SELECT  @nTrackPrice = [stats] FROM    syscon WHERE   [order] = 8 --判断是否启用价格跟踪  
    --SELECT  @nTrackDisCount = [stats] FROM    syscon WHERE   [order] = 46 --客户折扣跟踪  
    if exists(select 1 from sysdata where subname='ProcTypeName' and subvalue='FZBS')
		select @nTrackPrice=[stats],@nTrackDisCount=[stats] from syscon where [order]=case 
						when @nVchType in (6,7,34) then 211 
						when @nVchType in (8,11,24,45) then 212 
						when @nVchType in (211,212,218,221,222,223,224,234,232,230) then 214 
						else 0 end
    else
	begin
		SELECT  @nTrackPrice = [stats] FROM    syscon WHERE   [order] = 8 --判断是否启用价格跟踪
		SELECT  @nTrackDisCount = [stats] FROM    syscon WHERE   [order] = 46 --客户折扣跟踪  
	end
	select @nTrackPrice=isnull(@nTrackPrice,0),@nTrackDisCount=isnull(@nTrackDisCount,0)
    /*-----------------END----------------*/
    
    SELECT  @nModiSalePrice = [stats] FROM    syscon WHERE   [order] = 3 --销售单价自动修改商品的预设售价（折扣）  
    SET @dTempTotal = 0  
    SET @dTemptaxtotal = 0  
    SET @dTempTax_Total = 0  
    SET @dTempQty = 0  
    SET @dTotalMoney = 0  
    SET @dTotalinMoney = 0  
    SET @dTempCostTotal = 0  
    SET @SaleMoney = 0  
    SET @Vipdiscount_new = 0      
    SET @JoinCostPrice = 0  
    SET @JoinCostTotal = 0  
    SET @dTotalMoney1 = 0  
    SET @dTotalMoney2 = 0  
    SET @TempSaleMoney = 0  
    SET @CBTZ_YKCJE = 0  
    SET @CBTZ_XKCJE = 0  
    SET @xfje = 0  
    SET @xfje1 = 0  
    SET @xfje2 = 0  
    SET @dWinCashTotal = 0  
    SET @ifCan = 0  
    SET @temp_j = 0  


DECLARE @sign int --正负号
SET @sign =1
IF  @nVchType IN ( 34, 6,252 ) 
BEGIN
	EXEC @nret=modifydbfNEW  'bakdly',@nVchType,'',@nVchcode,@szktypeid,@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error
	if  @nVchtype = 6 
		SET @Sign =-1
	INSERT  INTO dlydata
    (
		vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,qty,price,total,costprice,costtotal,
		discount,discountprice,discounttotal,tax,taxprice,taxtotal,tax_total,comment,period,usedtype,costmode,
		unit,zddiscountprice,dtypeid,bargainTotal,ifsupply,colorid,[convert],packcode,packRate,packQty,branchid,BillType,
		CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,retailprice,vipdiscount,SaleMoney,
		vipcardid,OPID,Phrows,UnitRate,SingleUnit
    )
	SELECT 
		@nVchcode,@tDate,@nVchType,AtypeID,Ptypeid,@szBtypeid,@szEtypeid,@szKtypeId,@SIGN*Qty,Price,@SIGN*Total,
		round(CAST(costtotal/qty AS NUMERIC(24,10)),@dig_price),@SIGN*costTotal,
		discount,discountprice,@SIGN*discounttotal,tax,taxprice,@SIGN*taxtotal,@SIGN*tax_total,Comment,@period,usedtype,CostMode,
		unit,0,@deptid,@SIGN*bargainTotal,ifsupply,ColorID,@SIGN*[convert],packcode,packRate,packQty,@branchid,
		billtype,CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,--改billtype的取值modify by 老罗2012-09-13
		RetailPrice,vipdiscount,@Sign * SaleMoney,VipCardID,OPID,Phrows,UnitRate,SingleUnit
	FROM BakDly WHERE Vchcode =@nVchcode AND PtypeID<>'' ORDER BY DlyOrder
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  

	IF @nvchtype = 34 OR @nvchtype = 252 
		INSERT  INTO dlydatadetail
			(DlyOrder,Phrows,Vchcode,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],DiscountTotal,CostTotal,salemoney,usedtype)
		SELECT  
			a.DlyOrder,b.Phrows,b.vchcode,b.SIZEID,b.COLORID,b.QTY,b.Total,b.Taxtotal,b.Tax_total,
			round(CAST(cast(a.costtotal/a.qty as numeric(24,10)) * b.qty AS NUMERIC(24,10)),@dig_total),b.[Convert],b.DiscountTotal,
			round(CAST(cast(a.costtotal/a.qty as numeric(24,10)) * b.qty AS NUMERIC(24,10)),@dig_total),b.salemoney,a.usedtype
		FROM    BakDlyDetail b ,dlydata a where a.Vchcode =@nVchcode AND a.vchcode =b.vchcode and a.phrows=b.phrows  AND a.Ptypeid<>''
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  

	IF @nvchtype = 6 
		INSERT  INTO dlydatadetail
			(DlyOrder,Phrows,Vchcode,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],DiscountTotal,CostTotal,salemoney,usedtype)
		SELECT  a.DlyOrder,b.Phrows,b.vchcode,b.SIZEID,b.COLORID,-1 * b.QTY,-1 * b.Total,-1 * b.Taxtotal,-1 * b.Tax_total,-1 * b.BargainTotal,
				-1 * b.[Convert],-1 * b.DiscountTotal,
				round(-1 * CAST(cast(a.costtotal/a.qty as numeric(24,10)) * b.qty AS NUMERIC(24,10)),@dig_total),-1 * b.salemoney,a.usedtype
		FROM    BakDlyDetail b ,dlydata a where a.Vchcode =@nVchcode AND a.vchcode =b.vchcode and a.phrows=b.phrows AND a.Ptypeid<>''
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  

	--分摊成本金额
	if exists(select 1 
	          from dlydata a,
				(select sum(Costtotal) as Costtotal,sum(bargaintotal) as bargaintotal,dlyorder 
				 from dlydatadetail 
				 where vchcode = @nVchcode  group by dlyorder)b 
              where a.vchcode = @nVchcode and a.dlyorder = b.dlyorder and (a.costtotal <> b.costtotal or a.bargaintotal <> b.bargaintotal))
	BEGIN
		IF @nvchtype = 34 OR @nvchtype = 252  --要多分摊Bargaintotal
		BEGIN
			update dlydatadetail set  costtotal = ff.costtotal+ (b.costtotal- a.costtotal) ,
				bargaintotal = ff.bargaintotal+ (b.bargaintotal- a.bargaintotal)  
			from
				 (select vchcode,round(sum(costtotal),@dig_total) as costtotal,
				    round(SUM(bargaintotal),@dig_total) as bargaintotal,dlyorder 
				  from dlydatadetail 
				  where vchcode =@nVchcode  group by dlyorder,vchcode) a ,
				 dlydata b,
				 dlydatadetail ff
			where
				b.vchcode =@nVchcode
				AND ff.vchcode =@nVchcode
				AND a.dlyorder=b.dlyorder and a.dlyorder = ff.dlyorder  and (a.costtotal <> b.costtotal or a.bargaintotal <> b.bargaintotal)
				and exists(
					select 1 from (select top 1 colorid,sizeid 
					from dlydatadetail c where c.vchcode =@nVchcode AND ff.dlyorder = c.dlyorder order by colorid,sizeid) cc  where 
					ff.colorid = cc.colorid and ff.sizeid = cc.sizeid )
		            IF  @@error <> 0 
		            BEGIN  
		                SET @nRet = -2  
		                GOTO error  
		            END  
		END
		ELSE
			update dlydatadetail set  costtotal = ff.costtotal+ (b.costtotal- a.costtotal)  
			from
				 (select vchcode,round(sum(costtotal),@dig_total) as costtotal, dlyorder 
				 from dlydatadetail 
				 where vchcode =@nVchcode  group by dlyorder,vchcode) a ,
				 dlydata b,dlydatadetail ff
			where
				b.vchcode =@nVchcode
				AND ff.vchcode =@nVchcode
				AND a.dlyorder=b.dlyorder and a.dlyorder = ff.dlyorder  and a.costtotal <> b.costtotal 
				and exists(select 1 from (select top 1 colorid,sizeid 
										  from dlydatadetail c 
										  where c.vchcode =@nVchcode AND ff.dlyorder = c.dlyorder
										  order by colorid,sizeid) cc 
								   where ff.colorid = cc.colorid and ff.sizeid = cc.sizeid )
	            IF  @@error <> 0 
	            BEGIN  
	                SET @nRet = -2  
	                GOTO error  
	            END  
	END
	--凭证 现金银行科目
	DECLARE @INflag INT--收款标志
	if  @nVchtype = 34 
		SET @Sign =-1
	ELSE
		SET @Sign =1
		
	--判断付款机构和采购机构是否是同一机构 CS没有第三方结算
	if @procType='FZCS' or (@procType='FZBS' and exists (select 1 from dlyndx where vchcode=@nVchcode and (branchid3='' or branchid3=branchid )))
	BEGIN
		INSERT  INTO dlya
			(vchcode,Date,VchType,ATypeID,BTypeID,ETypeID,KTypeID,Total,period,UsedType,comment,Dtypeid,branchid,BillType)
		SELECT 
			@nVchcode,Date,@nVchType,Atypeid,@szBtypeid,@szEtypeid,@szKtypeId,@Sign*Total,@period,usedtype,comment,@deptid,branchid,1
		FROM BakDly WHERE Vchcode =@nVchcode AND PtypeID=''
		IF @@ROWCOUNT <>0
			SET @INflag =1
    
		--凭证 库存商品增加
		SELECT @bargainTotal=SUM(bargainTotal),@dTempTaxtotal=SUM(taxtotal),
		     @dTempTax_total=sum(tax_total),@dTempCostTotal=SUM(CostTotal)
		FROM BakDly 
		WHERE Vchcode =@nVchcode AND PtypeID<>''

		SET @dTemp=@bargainTotal
		IF @nVchType= 252 	 
			SET @dTemp =@dTempCostTotal
		IF  @nVchType= 6
			SET @dTemp =-@dTempCostTotal

		--库存商品增加   
	
		INSERT  INTO dlya
		(
		vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,comment,Dtypeid,branchid,BillType
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@GOODS_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTemp,@period,'','',@deptid,@branchid,1
		)  

            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  
		--应交税金
		IF @dTempTaxtotal<>0 AND @nvchtype IN (34,6)
		BEGIN
			IF @nvchtype=34
				SET @dtemptaxTotal=-@dtemptaxTotal
			INSERT  INTO dlya(vchcode,Date,VchType,ATypeID,BTypeID,ETypeID,KTypeID,Total,period,UsedType,comment,Dtypeid,branchid,BillType)
			SELECT @nVchcode,@tDate,@nVchType,@TAX_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTempTaxtotal,@period,'','',@deptid,@branchid,1
		END
		-- 应收应付
		SET @dTotalInMoney =0 --收款金额
		IF @nvchtype <>252 --其它入库单不存在此科目
		BEGIN
			IF 	@INflag =1
				SELECT @dTotalInMoney=sum(total) FROM BakDly WHERE Vchcode =@nVchcode AND PtypeID=''
			SET @dTemp = @dTempTax_total - @dTotalInMoney
			IF @nVchType =6
				SET @dTemp =-@dTemp
			--更新应收应付
			IF @procType = 'FZCS'
				EXEC FZUpdateYSYFTotal @dTemp, @szBtypeid, @nVchcode, @branchid,@nvchtype  
			INSERT  INTO dlya(vchcode,Date,VchType,ATypeID,BTypeID,ETypeID,KTypeID,Total,period,UsedType,comment,Dtypeid,branchid,BillType)
			SELECT @nVchcode,@tDate,@nVchType,@AP_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTemp,@period,'','',@deptid,@branchid,1
		END
		----进货与退货差价  
		IF @nVchType = 6 
		BEGIN  
			SELECT  @dTemp = @bargainTotal- @dTempCostTotal  
			IF @dTemp <> 0 
			BEGIN     
				INSERT  INTO dlya
				(
				vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType
				)
				VALUES  (
				@nVchcode,@tDate,@nVchType,@BUY_BUYBACK_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTemp,@period,'',@deptid,@branchid,1
				)  
			END
		END

		IF @nvchtype =252  --其它入库单会计科目 
		BEGIN
			SELECT TOP 1 @opid=opid FROM bakdly WHERE Vchcode =@nVchcode AND PtypeID<>''
			IF not EXISTS(SELECT  1 FROM OperationInfo WHERE optype=5 AND opid=@opid)  --出库类型没有对应会计科目，报错
			BEGIN  
				SET @nRet = -2  
				GOTO error  
			END 
			DECLARE @AtypeidIn VARCHAR(50)
			SET @AtypeidIn=''
			SELECT  @AtypeidIn= atypeid FROM OperationInfo WHERE optype=5 AND opid=@opid
			IF @AtypeidIn=''
			BEGIN  
				SET @nRet = -2  
				GOTO error  
			END 
		
			INSERT  INTO dlya
			(
			vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType
			)
			VALUES  (
			@nVchcode,@tDate,@nVchType,@AtypeidIn,@szBtypeid,@szEtypeid,@szKtypeid,
			case when left(@AtypeidIn,5) in ('00001','00004') then -@dTemp else @dTemp end,
			@period,'',@deptid,@branchid,2
			)  

		END

	
		----更改唯一码关联 Dlyorder			
		IF @procType = 'FZCS'
		BEGIN
            EXEC @nRet= GP_UpdatePtypeuniquecode  @nVchcode
			IF @nRet<>0
            GOTO error  
		END

		--**##价格跟踪，最近进价待写

		EXEC @nret=modifydbfNEW   'dlya',@nVchType,'',@nVchcode,'',@szptypeid OUTPUT,-1,@OldVchcode
		IF @nret<0
			GOTO error

		-------------如果该进货单是通过进货订单的来的，则处理进货订单的到货数量  
		IF @OrderList <> '' 
		BEGIN  
			EXEC @retOrder= FZOrderCheck @nvchcode, 7, @OrderList  
			IF @retOrder <> 0 
			BEGIN  
				SET @nRet = @retOrder  
				GOTO error  
			END  
		END  
		IF @nvchtype = 34  
		BEGIN
			--更新最近进价
			SELECT VchCode,ptypeid,discountprice,price INTO #bakdly FROM bakdly  WHERE  vchcode =@nVchcode AND ptypeid<>'' ORDER BY PHROWS DESC
			UPDATE  ptype 
			SET  recprice = b.discountprice,recprice1 = b.price 
			FROM Ptype p INNER JOIN #bakdly b ON p.typeid=b.ptypeid 
			WHERE   b.vchcode =@nVchcode AND b.ptypeid<>''
			IF OBJECT_ID(N'[tempdb].dbo.[#bakdly]','U') IS NOT NULL
			DROP TABLE #bakdly
			--价格跟踪
			EXEC FZGetCustomerPriceNew 'CB',@szBtypeid,@branchid,@nVchcode,@nTrackPrice,@nTrackDiscount
			--补货
			EXEC @nRet=GP_UpdatePtypeSupply @nVchcode,@nVchtype
			IF ( @@rowcount < 0 OR @@error <> 0) 
			BEGIN  
				SET @nRet = -2  
				GOTO error  
			END 
		END
	END
	else  --FZBS第三方结算  只处理34,6
	begin    
		--凭证 库存商品增加 
		SELECT @bargainTotal=SUM(bargainTotal),@dTempTaxtotal=SUM(taxtotal),@dTempTax_total=sum(tax_total),
		       @dTempCostTotal=SUM(CostTotal) 
		FROM BakDly WHERE Vchcode =@nVchcode AND PtypeID<>''

		SET @dTemp=@bargainTotal
		IF  @nVchType= 6
			SET @dTemp =-@dTempCostTotal

		--非结算机构 库存商品变化   
		INSERT  INTO dlya
		(
		vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,comment,Dtypeid,branchid,BillType
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@GOODS_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTemp,@period,'','',@deptid,@branchid,1
		)  
		--非结算机构内部结算 变化
		INSERT  INTO dlya
		(
		vchcode,[Date],vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@InnerSettlement_ID,@szBtypeid,@szEtypeid,@szKtypeId,-@dTemp,@period,'',@deptid,@branchid,1
		) 
		
		IF  @@error <> 0 
        BEGIN  
            SET @nRet = -2  
            GOTO error  
        END  
			
		--结算机构内部结算变化
		INSERT  INTO dlya
		(vchcode,Date,VchType,ATypeID,BTypeID,ETypeID,KTypeID,Total,period,UsedType,comment,Dtypeid,branchid,BillType)
		SELECT 
			@nVchcode,Date,@nVchType,Atypeid,@szBtypeid,@szEtypeid,@szKtypeId,@Sign*Total,@period,usedtype,comment,@deptid,branchid,1
		FROM BakDly WHERE Vchcode=@nVchcode AND PtypeID=''
		IF @@ROWCOUNT <>0
			SET @INflag =1
			
		INSERT  INTO dlya
		(
		vchcode,[Date],vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@InnerSettlement_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTemp,@period,'',@deptid,@branchid3,1
		) 
		
		IF  @@error <> 0 
        BEGIN  
            SET @nRet = -2  
            GOTO error  
        END  

        --下面处理结算机构 会计科目 
		--应交税金
		IF @dTempTaxtotal<>0 AND @nvchtype IN (34,6)
		BEGIN
			IF @nvchtype=34
				SET @dtemptaxTotal=-@dtemptaxTotal
			INSERT  INTO dlya(vchcode,Date,VchType,ATypeID,BTypeID,ETypeID,KTypeID,Total,period,UsedType,comment,Dtypeid,branchid,BillType)
			SELECT @nVchcode,@tDate,@nVchType,@TAX_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTempTaxtotal,@period,'','',@deptid,@branchid3,1
		END
		-- 应收应付
		SET @dTotalInMoney =0 --收款金额
		IF @nvchtype <>252 --其它入库单不存在此科目
		BEGIN
			IF 	@INflag =1
				SELECT @dTotalInMoney=sum(total) FROM BakDly WHERE Vchcode =@nVchcode AND PtypeID=''
			SET @dTemp = @dTempTax_total - @dTotalInMoney
			IF @nVchType =6
				SET @dTemp =-@dTemp
			--更新应收应付
			INSERT  INTO dlya(vchcode,Date,VchType,ATypeID,BTypeID,ETypeID,KTypeID,Total,period,UsedType,comment,Dtypeid,branchid,BillType)
			SELECT @nVchcode,@tDate,@nVchType,@AP_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTemp,@period,'','',@deptid,@branchid3,1
		END
		----进货与退货差价  
		IF @nVchType = 6 
		BEGIN  
			SELECT  @dTemp = @bargainTotal- @dTempCostTotal  
			IF @dTemp <> 0 
			BEGIN     
				INSERT  INTO dlya
				(
				vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType
				)
				VALUES  (
				@nVchcode,@tDate,@nVchType,@BUY_BUYBACK_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTemp,@period,'',@deptid,@branchid3,1
				)  
			END
		END

		--**##价格跟踪，最近进价待写
		EXEC @nret=modifydbfNEW   'dlya',@nVchType,'',@nVchcode,'',@szptypeid OUTPUT,-1,@OldVchcode
		IF @nret<0
			GOTO error

		-------------如果该进货单是通过进货订单的来的，则处理进货订单的到货数量  
		IF @OrderList <> '' 
		BEGIN  
			EXEC @retOrder= FZOrderCheck @nvchcode, 7, @OrderList  
			IF @retOrder <> 0 
			BEGIN  
				SET @nRet = @retOrder  
				GOTO error  
			END  
		END  
		IF @nvchtype = 34  
		BEGIN
			--更新最近进价
			SELECT VchCode,ptypeid,discountprice,price INTO #bakdly_settlement FROM bakdly  WHERE  vchcode =@nVchcode AND ptypeid<>'' ORDER BY PHROWS DESC
			UPDATE  ptype 
			SET     recprice = b.discountprice,recprice1 = b.price 
			FROM Ptype p INNER JOIN #bakdly_settlement b ON p.typeid=b.ptypeid 
			WHERE   b.vchcode =@nVchcode AND b.ptypeid<>''
			IF OBJECT_ID(N'[tempdb].dbo.[#bakdly_settlement]','U') IS NOT NULL
			DROP TABLE #bakdly_settlement
			--价格跟踪
			EXEC FZGetCustomerPriceNew 'CB',@szBtypeid,@branchid,@nVchcode,@nTrackPrice,@nTrackDiscount
			--补货
			EXEC @nRet=GP_UpdatePtypeSupply @nVchcode,@nVchtype
			IF ( @@rowcount < 0 OR @@error <> 0) 
			BEGIN  
				SET @nRet = -2  
				GOTO error  
			END 
		END 
			
	end

	GOTO VIP 
END
	

IF  @nVchType IN ( 11, 12, 222, 232, 100, 226,251 ) 
BEGIN
	SET @sign =-1
	IF @nVchType=232
		SET @sign =1

	 --配货时，成交金额为0，作为加盟入库成本，应该作为0成本入库  
	IF @nVchType=232
    	UPDATE bakdly SET Costmode = 4 WHERE Vchcode =@nVchcode AND PtypeID<>'' AND bargainTotal = 0 
	IF @nVchType IN (222,232)
    	UPDATE bakdly SET Costmode = 4 WHERE Vchcode =@nVchcode AND PtypeID<>'' AND Costmode IN (5, 6 )

	IF @nVchType IN ( 12, 100, 226 )
		UPDATE bakdly SET costtotal = costprice WHERE Vchcode =@nVchcode AND PtypeID<>'' AND qty=0

	IF @nVchType = 222  --由于bakdly中的ktypeid都只为dlyndx中的ktypeid, 而配货则应该为 ktypeid2  
    BEGIN  
        SET @szktypeid = @szktypeidT2  
        SET @BranchID = @branchidT2  
    END  
	EXEC @nret=modifydbfNEW  'bakdly',@nVchType,'',@nVchcode,@szktypeid,@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error
	INSERT  INTO dlydata
    (
      vchcode, Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,qty,price,total,costprice,costtotal,
      discount,discountprice,discounttotal,tax,taxprice,taxtotal,tax_total,comment,period,usedtype,costmode,
      unit,dtypeid,bargainTotal,ifsupply,colorid,[convert],packcode,packRate,packQty,branchid,BillType,
      CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,retailprice,vipdiscount,SaleMoney,vipcardid,OPID,
	  JoinCostPrice,JoincostTotal,ForeignDlyorder,salemode,marketdiscount,marketdiscount1,Phrows,UnitRate,SingleUnit
    )
	SELECT   ---**## 零售数量为0时，应该反写 CostPrice
		  @nVchcode,[Date],VchType,AtypeID,Ptypeid,@szBtypeid,@szEtypeid,@szKtypeId,
	      @sign*Qty,
	      case WHEN VchType =251 then round(CAST(costtotal/qty AS NUMERIC(24,10)),@dig_price) else Price end as price,  
	      case when VchType =251 then @SIGN *costtotal else  case when  Qty = 0 THEN Total  ELSE @SIGN *Total END END as total,
	      case when qty=0 then costprice else round(CAST(costtotal/qty  AS NUMERIC(24,10)),@dig_price) end as costprice,
	      @SIGN *costtotal,discount,discountprice,
	      CASE WHEN Qty = 0 THEN discounttotal else @sign*discounttotal end as discounttotal, 
	      tax,
	      taxprice,CASE WHEN Qty = 0 THEN taxtotal else @sign*taxtotal end as taxtotal,
		  CASE WHEN Qty = 0 THEN tax_total else @sign*tax_total end as tax_total,
	      comment,@period,
	      CASE usedtype WHEN '3' THEN '' ELSE usedtype END,
	      CostMode,unit,@deptid,
	      CASE WHEN Qty = 0 THEN bargainTotal  ELSE @SIGN *bargainTotal END,
			ifsupply,ColorID,@sign*[convert],packcode,packRate,packQty,@Branchid,billtype,--改billtype的取值modify by 老罗2012-09-13
			CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,RetailPrice,Vipdiscount,
			CASE WHEN Qty = 0 THEN salemoney   ELSE @SIGN * salemoney  END,
			Case when VchType in (12,100) then vipcardid else @LSVipCardid end,
		    OPID, 
			case when qty=0 then costprice else round(CAST(costtotal/qty AS NUMERIC(24,10)),@dig_price) end ,
			@SIGN *costtotal  as JoincostTotal,
		    dlyorder as ForeignVchcode,
		    salemode,
		    marketdiscount,
		    marketdiscount1,Phrows,UnitRate,SingleUnit
	FROM BakDly 
	WHERE Vchcode =@nVchcode AND PtypeID<>''
	ORDER BY DlyOrder
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  

	INSERT  INTO dlydatadetail
	(
	DlyOrder,Phrows,Vchcode,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,
	[Convert],DiscountTotal,CostTotal,salemoney,JoincostTotal,usedtype
	)
    SELECT  a.DlyOrder ,
            b.phrows ,
            b.vchcode ,
            b.SIZEID ,
            b.COLORID ,
            @SIGN * b.QTY ,
            CASE WHEN VchType = 251
                 THEN @SIGN * ROUND(Cast(( CASE WHEN a.qty = 0 THEN a.costprice
                                           ELSE CAST(a.costtotal / a.qty AS NUMERIC(24,10))
                                      END ) * b.qty AS numeric(24,10)), @dig_total)
                 ELSE ROUND(@SIGN * b.Total,@dig_total)
            END ,
            @SIGN * b.Taxtotal ,
            @SIGN * b.Tax_total ,
            @SIGN * b.BargainTotal ,
            @SIGN * b.[Convert] ,
            @SIGN * b.DiscountTotal ,
            @SIGN * ROUND(Cast(( CASE WHEN a.qty = 0 THEN a.costprice
                                 ELSE CAST(a.costtotal / a.qty AS NUMERIC(24,
                                                              10))
                            END ) * b.qty AS numeric(24,10)), @dig_total) ,
            @SIGN * b.salemoney ,
            @SIGN * ROUND(Cast(( CASE WHEN a.qty = 0 THEN a.costprice
                                 ELSE CAST(a.costtotal / a.qty AS NUMERIC(24,
                                                              10))
                            END ) * b.qty AS numeric(24,10)), @dig_total) ,
            a.usedtype
    FROM    BakDlyDetail b ,
            dlydata a
    WHERE   a.Vchcode = @nVchcode
            AND b.Vchcode = @nVchcode
            AND a.phrows = b.phrows
            AND a.Ptypeid <> ''
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  
    
    --modify by 老罗  2012-09-29 处理其他出入库单dlyndx中金额与单据明细金额不等的问题
    IF @nVchType=251   
    BEGIN
		UPDATE dlyndx SET dlyndx.Total=b.CostTotal FROM 
			(SELECT SUM(CostTotal) costTotal FROM 
				bakdly  WHERE  vchtype=251 AND vchcode=@nvchcode) b
			WHERE dlyndx.vchcode=@nvchcode AND dlyndx.vchtype=251
    END        
	--分摊成本金额
	if exists(select  1 from dlydata a,(select sum(Costtotal) as Costtotal,dlyorder from dlydatadetail where vchcode = @nVchcode   group by dlyorder)b 
               where a.vchcode = @nVchcode and a.dlyorder = b.dlyorder and a.costtotal <> b.costtotal)
		update dlydatadetail 
		set 
			costtotal = ff.costtotal+ (b.costtotal- a.costtotal)  
		from
			 (select vchcode,round(sum(costtotal),@dig_total) as costtotal, dlyorder 
			 from dlydatadetail
			 where vchcode =@nVchcode  group by dlyorder,vchcode) a ,
			 dlydata b,
			 dlydatadetail ff
		where
			b.vchcode =@nVchcode
			AND ff.vchcode =@nVchcode
			AND a.dlyorder=b.dlyorder and a.dlyorder = ff.dlyorder  and a.costtotal <> b.costtotal 
			and exists(
				select 1 from (select top 1 colorid,sizeid from dlydatadetail c where c.vchcode =@nVchcode 
				AND ff.dlyorder = c.dlyorder order by colorid,sizeid) cc  where 
				ff.colorid = cc.colorid and ff.sizeid = cc.sizeid )

	SELECT @SaleMoney=SUM(salemoney),@dTempCostTotal=SUM(CostTotal),
	       @dTempTaxtotal=SUM(taxtotal),@dTempTax_total=sum(tax_total),@dTempTotal=SUM(BargainTotal) 
	FROM bakdly WHERE Vchcode =@nVchcode AND PtypeID<>''
	IF @nvchtype NOT IN ( 100 )  --积分金额
	    SET @xfje = @dTempTax_total
	ELSE 
	    SET @xfje =  @SaleMoney 

	SET @vipsalemoneyTemp =@SaleMoney
	--凭证
	INSERT  INTO dlya(vchcode,Date,VchType,ATypeID,BTypeID,ETypeID,KTypeID,Total,period,UsedType,comment,Dtypeid,branchid,BillType,vipcardid)	--VIP储值,预收账款,加盟验收单取负
	SELECT @nVchcode,Date,@nVchType,Atypeid,@szBtypeid,@szEtypeid,@szKtypeId,
	case when vchtype=232 or atypeid in ('0000299999','0000200888') then -Total else total end as total,
	@period,usedtype,comment,@deptid,case when vchtype =222 then @branchidT2 else branchid end,2,vipcardid
	FROM BakDly WHERE Vchcode =@nVchcode AND PtypeID=''
	IF @@ROWCOUNT <>0
		SET @INflag =1


	--凭证 库存商品减少

    IF @dTempCostTotal <> 0  OR (@dTempCostTotal =0 AND @nVchType in (251,222,232)) 
		INSERT  INTO dlya(vchcode,Date,VchType,ATypeID,BTypeID,ETypeID,KTypeID,Total,period,UsedType,comment,Dtypeid,branchid,BillType)
		SELECT @nVchcode,@tDate,@nVchType,@GOODS_ID,@szBtypeid,@szEtypeid,@szKtypeId,@sign*@dTempCostTotal,@period,'','',@deptid,@branchid,1
	--销售成本   
	IF @nvchtype <> 232 AND  @nvchtype <>251
	    INSERT  INTO dlya
	            (
		          vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType
		        )
	    VALUES  (
	              @nVchcode,@tDate,@nVchType,@SALE_COST_ID,@szBtypeid,@szEtypeid,@szKtypeid,-1*@sign* @dTempCostTotal,@period,'',@deptid,@branchid,2
	            ) 

	--应交税金
	IF @dTempTaxtotal <> 0 OR @nvchtype = 100 
		INSERT  INTO dlya(vchcode,Date,VchType,ATypeID,BTypeID,ETypeID,KTypeID,Total,period,UsedType,comment,Dtypeid,branchid,BillType)
		SELECT @nVchcode,@tDate,@nVchType,@TAX_ID,@szBtypeid,@szEtypeid,@szKtypeId,-1*@sign*@dTempTaxtotal,@period,'','',@deptid,@branchid,1
	--销售收入 
	IF @nvchtype <> 232  AND @nvchtype <>251
		INSERT  INTO dlya
		        (
		          vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType
		        )
		VALUES  (@nVchcode,@tDate,@nVchType,@SALE_INCOME_ID,@szBtypeid,@szEtypeid,@szKtypeid,-1*@sign*@dTempTotal,@period,'',@deptid,@branchid,2
		        )  
	-- 应收应付
	 IF @nvchtype=100
		 SET @dTemp = ISNULL(@dTempTax_Total, 0) 
	SET @dTotalInMoney =0 --收款金额
	IF 	@INflag =1
		SELECT @dTotalInMoney=sum(total) FROM BakDly WHERE Vchcode =@nVchcode AND PtypeID=''
	SET @dTemp = @dTempTax_total - @dTotalInMoney

	  

	IF @nvchtype =251  --其它出库单会计科目 
    BEGIN
		SELECT TOP 1 @opid=opid FROM bakdly WHERE Vchcode =@nVchcode AND PtypeID<>''
    	IF NOT EXISTS(SELECT  1 FROM OperationInfo WHERE optype=4 AND opid=@opid)  --出库类型没有对应会计科目，报错
		BEGIN  
            SET @nRet = -2  
            GOTO error  
        END 
		DECLARE @AtypeidOut VARCHAR(50)
		SELECT  @AtypeidOut= atypeid FROM OperationInfo WHERE optype=4 AND opid=@opid
		IF @AtypeidOut=''
		BEGIN  
            SET @nRet = -2  
            GOTO error  
        END 
		INSERT  INTO dlya(vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType)
        VALUES  ( @nVchcode,@tDate,@nVchType,@AtypeidOut,@szBtypeid,@szEtypeid,@szKtypeid,
                  case when left(@AtypeidOut,5) in ('00001','00004') then @dTempCostTotal else -@dTempCostTotal end,
                  @period,'',@deptid,@branchid,2)  
        IF ( @@rowcount < 0 OR @@error <> 0 ) 
        BEGIN  
            SET @nRet = -2  
            GOTO error  
        END 
	END		
 	--加盟商配货验收及加盟商退货验收单 checkandaccept =1  
	IF @nvchtype IN (232,224)
    	UPDATE  dlyndx SET checkandaccept =1 WHERE   vchcode = @nVchcode 

    ----更改唯一码关联 Dlyorder			
	IF @procType = 'FZCS'
	BEGIN
        EXEC @nRet= GP_UpdatePtypeuniquecode  @nVchcode
		IF @nRet<>0
        GOTO error  
		IF @nvchtype IN (222,232) 
			EXEC FZUpdateYSYFTotal @dTemp, @szBtypeid, @nVchcode,@branchidT2,@nvchtype  
		ELSE 
			EXEC FZUpdateYSYFTotal @dTemp, @szBtypeid, @nVchcode,@branchidT,@nvchtype
	END
	IF @nvchtype = 232 --应付  
        INSERT  INTO dlya
                (
		          vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType
		        )
        VALUES  (
                  @nVchcode,@tDate,@nVchType,@AP_ID,@szBtypeid,@szEtypeid,@szKtypeid,@sign*@dTemp,@period,'',@deptid,@branchid,2
                )  
    ELSE IF @nvchtype <>251--应收  
        INSERT  INTO dlya
                (
		          vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType
		        )
        VALUES  (
                  @nVchcode,@tDate,@nVchType,@AR_ID,@szBtypeid,@szEtypeid,@szKtypeid,-1*@sign*@dTemp,@period,'',@deptid,@branchid,2
                ) 
	--会计科目过账
	EXEC @nret=modifydbfNEW   'dlya',@nVchType,'',@nVchcode,@szktypeid,@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error
	--价格跟踪
	IF @nVchType =11
		EXEC FZGetCustomerPriceNew 'XS',@szBtypeid,@branchid,@nVchcode,@nTrackPrice,@nTrackDiscount
	IF @nVchType =222  --收货机构
		EXEC FZGetCustomerPriceNew 'PH',@szBtypeid,@branchidT,@nVchcode,@nTrackPrice,@nTrackDiscount

	-------如果该销售单是通过订单的来的，则处理订单的数量  
	IF @OrderList <> '' 
	BEGIN  
	    IF @nvchtype <> 232 
        BEGIN  
            IF @nvchtype = 222 
                EXEC @retOrder= FZOrderCheck @nVchcode,221, @OrderList  
            ELSE 
                EXEC @retOrder= FZOrderCheck @nVchcode,8, @OrderList  
            SET @retOrder = ISNULL(@retOrder, 0)  
            IF @retOrder <> 0 
            BEGIN  
                SET @nRet = @retOrder  
                GOTO error  
            END  
        END  
	END  

    -------------------------------更新补货记录表--------------------------------------------Begin  
	IF @nVchType IN (11,222,232,251) 
	BEGIN  
		EXEC @nRet=GP_UpdatePtypeSupply @nVchcode,@nVchtype
		IF ( @@rowcount < 0 OR @@error <> 0) 
		BEGIN  
			SET @nRet = -2  
			GOTO error  
		END  
	END  
     ---------------------------------------------------------------更新补货记录表--------------------------------------------End   
	GOTO VIP 
END
	
IF @nVchType IN ( 45, 13, 224, 234, 101, 227 )  --13,227,101 零售销售退货单,加盟店零售退货单,商场专柜零售退货单 不存在这三张单据了
BEGIN
	IF @nVchType = 234 --由于bakdly中的ktypeid都只为dlyndx中的ktypeid, 而配货退货则应该为 ktypeid2  
    BEGIN  
        SET @szktypeid = @szktypeidT2  
        SET @BranchID = @branchidT2  
    END  
	IF @nVchtype=234
		SET @SIGN =-1
	 IF @nvchtype = 234 
    	UPDATE bakdly SET Costmode =case When Costmode = 4 Then 0 Else 4 End  WHERE Vchcode =@nVchcode AND PtypeID<>'' AND Costmode IN (4,5, 6 )
-- 	IF @nvchtype = 234  --翻译如下
-- 		SET @dCostTotal = @JoincostTotal  
	--IF @nvchtype = 234 
    --	UPDATE bakdly SET CostTotal = joincosttotal WHERE Vchcode =@nVchcode AND PtypeID<>'' 

	EXEC @nret=modifydbfNEW  'bakdly',@nVchType,'',@nVchcode,@szktypeid,@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error
	INSERT  INTO dlydata
	(
	vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,qty,price,total,costprice,costtotal,
	discount,discountprice,discounttotal,tax,taxprice,taxtotal,tax_total,comment,period,usedtype,costmode,
	unit,bargainTotal,ifsupply,colorid,[convert],JoinCostPrice,JoinCostTotal,vipdiscount,salemode,salemoney,
	packcode,packRate,packQty,Dtypeid,ForeignDlyorder,branchid,BillType,CustValue1,CustValue2,CustValue3,
	CustValue4,CustValue5,CustValue6,RetailPrice,marketdiscount,marketdiscount1,vipcardid,OPID,Phrows,UnitRate,SingleUnit
	)
	SELECT
		@nVchcode,[Date],VchType,AtypeID,Ptypeid,@szBtypeid,@szEtypeid,@szKtypeId,@Sign*qty,Price,@Sign*Total,
		round(CAST(costtotal/qty AS NUMERIC(24,10)),@dig_price),@Sign*costtotal,
		discount,discountprice,@Sign* discounttotal,tax,taxprice,@Sign*taxtotal,@Sign*tax_total,Comment,@period,
		CASE usedtype WHEN '3' THEN '' ELSE usedtype END,CostMode,
		unit,@Sign*bargainTotal,ifsupply,ColorID,@Sign*[convert],
		round(CAST(costtotal/qty AS NUMERIC(24,10)),@dig_price),@Sign*Costtotal,vipdiscount,salemode,@Sign*salemoney,
		packcode,packRate,packQty,@deptid,dlyorder,@Branchid,2 as billtype,CustValue1,CustValue2,CustValue3,
		CustValue4,CustValue5,CustValue6,RetailPrice,marketdiscount,marketdiscount1,@VipCardID,OPID,Phrows,UnitRate,SingleUnit
	FROM BakDly WHERE Vchcode =@nVchcode AND PtypeID<>''
	ORDER BY DlyOrder
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  
	
	INSERT  INTO dlydatadetail
	(
	DlyOrder,Phrows,vchcode,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],DiscountTotal,CostTotal,salemoney,JoincostTotal,usedtype
	)
	SELECT  a.DlyOrder,b.phrows,b.vchcode,b.SIZEID,b.COLORID,@sign*b.QTY,@sign*b.Total,@sign*b.Taxtotal,@sign*b.Tax_total,
	@sign*b.BargainTotal,@sign*b.[Convert],@sign*b.DiscountTotal,
	@SIGN *round(CAST((case when a.qty=0 then a.costprice else cast(a.costtotal/a.qty as numeric(24,10)) END )*b.qty AS numeric(24,10)),@dig_total),
	@sign*b.salemoney,
	@SIGN *round(CAST((case when a.qty=0 then a.costprice else cast(a.costtotal/a.qty as numeric(24,10)) end)*b.qty AS numeric(24,10)),@dig_total),
	b.usedtype
	FROM    BakDlyDetail b ,dlydata a where a.Vchcode =@nVchcode AND a.vchcode =b.vchcode and a.phrows=b.phrows 
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  

	--分摊成本金额
	if exists(select  1 from dlydata a,(select sum(Costtotal) as Costtotal,dlyorder from dlydatadetail where vchcode = @nVchcode   group by dlyorder)b 
               where a.vchcode = @nVchcode and a.dlyorder = b.dlyorder and a.costtotal <> b.costtotal)
		update dlydatadetail 
		set 
			costtotal = ff.costtotal+ (b.costtotal- a.costtotal)  
		from
			 (select vchcode,round(sum(costtotal),@dig_total) as costtotal, dlyorder from dlydatadetail where vchcode =@nVchcode  group by dlyorder,vchcode) a ,
			 dlydata b,dlydatadetail ff
		where
			b.vchcode =@nVchcode
			AND ff.vchcode =@nVchcode
			AND a.dlyorder=b.dlyorder and a.dlyorder = ff.dlyorder  and a.costtotal <> b.costtotal 
			and exists(
				select 1 from (select top 1 colorid,sizeid from dlydatadetail c where c.vchcode =@nVchcode AND ff.dlyorder = c.dlyorder order by colorid,sizeid) cc  where 
				ff.colorid = cc.colorid and ff.sizeid = cc.sizeid )

	SELECT @vipsalemoneyTemp=-sum(SaleMoney),@dTempCostTotal=SUM(CostTotal),@dTempTaxtotal=SUM(taxtotal),@dTempTax_total=sum(tax_total),@dTempTotal=SUM(BargainTotal) FROM bakdly WHERE Vchcode =@nVchcode AND PtypeID<>''
    SET @xfje = -@dTempTax_total 


	-- 	SELECT  @SIGN =1
	-- 	IF @nvchtype = 234  OR @szAtypeid='0000200888'--加盟配货退货单\预收账款反号  
	-- 	    SELECT  @SIGN = -1
	-- 	IF @szAtypeid <> '0000299999'    AND @szATypeID <> @PREPERENTIAL_ID 
	--     BEGIN  
	--         SELECT  @SIGN = -1 * @SIGN  
	--     END  
	--凭证
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType,vipcardid,comment
	)
	select @nVchcode,Date,@nVchType,Atypeid,@szBtypeid,@szEtypeid,@szKtypeId,
	case WHEN @nvchtype = 234  OR Atypeid='0000200888' 
	     then -1* (case when (Atypeid <> '0000299999'  AND ATypeID <> @PREPERENTIAL_ID) 
	                 then -1 else 1 end)*total   
		 else case when (Atypeid <> '0000299999' AND ATypeID <> @PREPERENTIAL_ID) 
		           then -total 
		           else total end 
		 END Total,
		 @period,usedtype,@deptid,@branchid,2,VipCardID,COMMENT
	FROM BakDly WHERE Vchcode =@nVchcode AND PtypeID=''
	IF @@ROWCOUNT <>0
		SET @INflag =1
        if @procType <> 'FZCS' begin
		IF @nVchType = 234 --加盟退货出库的往来单位是 验收方机构对应往来单位  
			SELECT  @szBtypeid = BTypeID FROM    Branch WHERE   BranchID = @branchidT  
		IF @nVchType = 224 --盟配退货验收的往来单位是 退货机构对应往来单位  
			SELECT  @szBtypeid = BTypeID  FROM    Branch WHERE   BranchID = @branchidT2   
        end

	 --凭证 库存商品 
	IF @nvchtype = 234  
	    SELECT  @SIGN = -1
	ELSE
	    SELECT  @SIGN = 1
	INSERT  INTO dlya (vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType)
	VALUES  (@nVchcode,@tDate,@nVchType,@GOODS_ID,@szBtypeid,@szEtypeid,@szKtypeid,@SIGN*@dTempCostTotal,@period,'',@deptid,@branchid,2) 

	--凭证 应交税金减少  
    IF @nvchtype = 234  --配货退货的应交税金应该是增加  
        SET @dtemptaxTotal = -@dtemptaxTotal  

	IF @dTempTaxtotal <> 0
		INSERT  INTO dlya
		(
		vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@TAX_ID,@szBtypeid,@szEtypeid,@szKtypeid,-1 * @dtemptaxTotal,@period,'',@deptid,@branchid,2
		)  

	--凭证 销售收入  
	IF @nvchtype <> 234 
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType
	)
	VALUES  (
	@nVchcode,@tDate,@nVchType,@SALE_INCOME_ID,@szBtypeid,@szEtypeid,@szKtypeid,-1 * @dTempTotal,@period,'',@deptid,@branchid,2
	)  
	--凭证 销售成本 
	IF @nvchtype <> 234 
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType
	)
	VALUES  (
	@nVchcode,@tDate,@nVchType,@SALE_COST_ID,@szBtypeid,@szEtypeid,@szKtypeid,-1 * @dTempCostTotal,@period,'',@deptid,@branchid,2
	) 


	--应收应付  
	SET @dTotalMoney =@dTempTax_total
	SET @dTotalInMoney =0
	IF 	@INflag =1
		SELECT @dTotalInMoney=sum(total) FROM BakDly WHERE Vchcode =@nVchcode AND PtypeID=''

	IF @nvchtype <> 101 
	BEGIN  
	    SET @dTemp = -( @dTotalMoney - @dTotalInMoney - @dPreferential )  
	    --UPDATE  dlyndx  SET     Total = ABS(@dTotalMoney), qty = ABS(@dTempQty) WHERE   vchcode = @nVchcode  
	END  
	ELSE 
	BEGIN  
	    SELECT  @RI_temp = SUM(Total)    FROM    bakdly
	    WHERE   vchcode = @nVchcode  AND atypeid <> '0000100001'   
	    SET @dTempTax_Total = ( @dTempTax_Total )  - ISNULL(@RI_temp, 0)  
	    SET @dTemp = ISNULL(@dTempTax_Total, 0)  
	    --UPDATE  dlyndx SET     Total = ABS(@TempSaleMoney),qty = ABS(@dTempQty) WHERE   vchcode = @nVchcode  
	END  
	IF  @procType = 'FZCS'
	BEGIN
		IF @nvchtype = 234 
			EXEC FZUpdateYSYFTotal @dTemp, @szBtypeid, @nVchcode,@branchidT2,@nvchtype  
		ELSE 
			EXEC FZUpdateYSYFTotal @dTemp, @szBtypeid, @nVchcode,@branchidT,@nvchtype  
	END
	IF @nvchtype <> 234 --应收  
		INSERT  INTO dlya
		(vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@AR_ID,@szBtypeid,@szEtypeid,@szKtypeid,CASE WHEN @nVchType = 101 THEN -1 * @dTemp   ELSE @dTemp END,@period,'',@deptid,@branchid,2
		)  
	ELSE ----应付(加盟配货退货)  
		INSERT  INTO dlya
		(
		vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@AP_ID,@szBtypeid,@szEtypeid,@szKtypeid,CASE WHEN @nVchType = 101 THEN -1 * @dTemp   ELSE @dTemp END,@period,'',@deptid,@branchid,2
		)  
	
	IF @nvchtype = 234 --进货退货差价  
	BEGIN  
		SET @JHTHCJ =@dTempTotal
		SET @JHTHCJ = -@dTempCostTotal + @JHTHCJ  
		INSERT  INTO dlya
		(
		vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,BillType)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@BUY_BUYBACK_ID,@szBtypeid,@szEtypeid,@szKtypeid,@JHTHCJ,@period,'',@deptid,@branchid,2
		)  
	END  

	EXEC @nret=modifydbfNEW   'dlya',@nVchType,'',@nVchcode,@szktypeid,@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error
	-------------如果该销售单是通过订单的来的，则处理订单的数量  
	IF @OrderList <> '' 
	BEGIN  
		IF @nvchtype <> 224 
	    BEGIN  
	        IF @nvchtype = 234 
	            EXEC @retOrder= FZOrderCheck @nVchcode, 223,@OrderList  
	        ELSE 
	            EXEC @retOrder= FZOrderCheck @nVchcode, 8,@OrderList  
	        SELECT  @retOrder = ISNULL(@retOrder, 0)  
	        IF @retOrder <> 0 
	        BEGIN  
	            SET @nRet = @retOrder  
	            GOTO error  
	        END  
	    END  
	END  

	IF @nVchType = 224 --状态改成验收
		UPDATE  dlyndx SET     checkandaccept = 1 WHERE   vchcode = @nVchcode  AND vchtype = 224  

	----更改唯一码关联 Dlyorder			
	IF @procType = 'FZCS'
	BEGIN
            EXEC @nRet= GP_UpdatePtypeuniquecode  @nVchcode
			IF @nRet<>0
            GOTO error  
	END
	GOTO VIP
END
---销售换货单开始 BEGIN
IF @nVchType = 24 
BEGIN
	EXEC @nret=modifydbfNEW  'bakdly',@nVchType,'',@nVchcode,@szktypeid,@szptypeid OUTPUT,1,@OldVchcode
	IF @nret<0
		GOTO error
	EXEC @nret=modifydbfNEW  'bakdly',@nVchType,'',@nVchcode,@szktypeid2,@szptypeid OUTPUT,2,@OldVchcode
	IF @nret<0
	BEGIN
		select @szktypeid=@szktypeid2
		GOTO error
	END
	--出库
	INSERT  INTO Dlydata
	(
	vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,qty,price,total,costprice,costtotal,
	discount,discountprice,discounttotal,tax,taxprice,taxtotal,tax_total,comment,period,usedtype,costmode,
	unit,bargainTotal,ifsupply,colorid,[convert],vipdiscount,Salemode,salemoney,packcode,packRate,packQty,dtypeid,ForeignDlyorder,branchid,billtype,
	CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,RetailPrice,vipcardid,OPID,Phrows,UnitRate,SingleUnit
	)
	SELECT 
	@nVchcode,@tDate,@nVchType,AtypeId,Ptypeid,@szBtypeid,@szEtypeid,@szKtypeid2,-Qty,Price,-Total,round(costtotal/qty,@dig_price),-costTotal,
	discount,discountprice,-discounttotal,tax,taxprice,-taxtotal,-tax_total,comment,@period,usedtype,CostMode,
	unit,-bargainTotal,ifsupply,ColorID,[convert],Vipdiscount,salemode,-salemoney,packcode,packRate,packQty,@deptid,dlyorder,branchid,2,
	CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,RetailPrice,VipCardID,OPID,Phrows,UnitRate,SingleUnit
	FROM bakdly WHERE Vchcode =@nVchcode and usedtype=2 AND PtypeID<>''
    ORDER BY DlyOrder
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  
	SET @sign =-1

	INSERT  INTO dlydatadetail
	(
	DlyOrder,phrows,vchcode,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],DiscountTotal,CostTotal,salemoney,usedtype
	)
	SELECT  a.DlyOrder,b.phrows,b.vchcode,b.SIZEID,b.COLORID,@sign*b.QTY,@sign*b.Total,@sign*b.Taxtotal,@sign*b.Tax_total,@sign*b.BargainTotal,@sign*b.[Convert],@sign*b.DiscountTotal,
	@SIGN *round(CAST((case when a.qty=0 then a.costprice else cast(a.costtotal/a.qty as numeric(24,10)) end)*b.qty AS numeric(24,10)),@dig_total),
	@sign*b.salemoney,a.usedtype
	FROM    BakDlyDetail b ,dlydata a where a.Vchcode =@nVchcode AND a.vchcode =b.vchcode and a.phrows=b.phrows  and a.usedtype=2 and b.usedtype=2
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  
	--入库
	INSERT  INTO Dlydata
	(
	vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,qty,price,total,costprice,costtotal,
	discount,discountprice,discounttotal,tax,taxprice,taxtotal,tax_total,comment,period,usedtype,costmode,
	unit,bargainTotal,ifsupply,colorid,[convert],vipdiscount,Salemode,salemoney,packcode,packRate,packQty,
	dtypeid,ForeignDlyorder,branchid,billtype,CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,
	CustValue6,RetailPrice,vipcardid,OPID,Phrows,UnitRate,SingleUnit
	)
	SELECT 
	@nVchcode,@tDate,@nVchType,AtypeId,Ptypeid,@szBtypeid,@szEtypeid,Ktypeid,Qty,Price,Total,round(costtotal/qty,@dig_price),costTotal,
	discount,discountprice,discounttotal,tax,taxprice,taxtotal,tax_total,comment,@period,usedtype,CostMode,
	unit,bargainTotal,ifsupply,ColorID,[convert],Vipdiscount,salemode,salemoney,packcode,packRate,packQty,@deptid,dlyorder,branchid,2,
	CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,RetailPrice,VipCardID,OPID,Phrows,UnitRate,SingleUnit
	FROM bakdly WHERE Vchcode =@nVchcode  and usedtype=1 AND PtypeID<>''
	ORDER BY DlyOrder
    IF  @@error <> 0 
    BEGIN  
        SET @nRet = -2  
        GOTO error  
    END  
	INSERT  INTO dlydatadetail
	(
	DlyOrder,phrows,vchcode,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,
	[Convert],DiscountTotal,CostTotal,salemoney,usedtype
	)
	SELECT  a.DlyOrder,b.phrows,b.vchcode,b.SIZEID,b.COLORID,b.QTY,b.Total,b.Taxtotal,
	b.Tax_total,b.BargainTotal,b.[Convert],b.DiscountTotal,
	round(CAST((case when a.qty=0 then a.costprice else cast(a.costtotal/a.qty as numeric(24,10)) end)*b.qty AS numeric(24,10)),@dig_total),
	b.salemoney,a.usedtype
	FROM    BakDlyDetail b ,dlydata a 
	where a.Vchcode =@nVchcode AND a.vchcode =b.vchcode and a.phrows=b.phrows  and a.usedtype=1  and b.usedtype=1
    IF  @@error <> 0 
    BEGIN  
        SET @nRet = -2  
        GOTO error  
    END  
	--分摊成本金额
	if exists(select  1 from dlydata a,(select sum(Costtotal) as Costtotal,dlyorder from dlydatadetail where vchcode = @nVchcode   group by dlyorder)b 
               where a.vchcode = @nVchcode and a.dlyorder = b.dlyorder and a.costtotal <> b.costtotal)
		update dlydatadetail 
		set 
			costtotal = ff.costtotal+ (b.costtotal- a.costtotal)  
		from
			 (select vchcode,round(sum(costtotal),@dig_total) as costtotal, dlyorder from dlydatadetail
			  where vchcode =@nVchcode  group by dlyorder,vchcode) a ,
			 dlydata b,dlydatadetail ff
		where
			b.vchcode =@nVchcode
			AND ff.vchcode =@nVchcode
			AND a.dlyorder=b.dlyorder and a.dlyorder = ff.dlyorder  and a.costtotal <> b.costtotal 
			and exists(
				select 1 
				from 
					(select top 1 colorid,sizeid 
					 from dlydatadetail c 
					 where c.vchcode =@nVchcode AND ff.dlyorder = c.dlyorder 
					 order by colorid,sizeid) cc  
				where 
					ff.colorid = cc.colorid and ff.sizeid = cc.sizeid )

	SELECT @dTempCostTotal=SUM(case when usedtype=2 then -CostTotal else CostTotal end),
		@dTempTaxtotal=SUM(case when usedtype=2 then -taxtotal else taxtotal end),
		@dTempTax_total=sum(case when usedtype=2 then -tax_total else tax_total end),
		@dTempTotal=SUM(case when usedtype=2 then -BargainTotal else BargainTotal end) 
	FROM bakdly 
	WHERE Vchcode =@nVchcode AND PtypeID<>''
	
	SET @xfje =-@dTempTax_total
	SET @vipsalemoneyTemp =-@dTempTax_total
		
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,
	dtypeid,branchid,BillType,vipcardid,comment
	)
	SELECT @nVchcode,[Date],@nVchType,Atypeid,@szBtypeid,@szEtypeid,@szKtypeId,
		case when atypeid in ('0000299999','0000200888') then -Total else total end as total,
		@period,usedtype,@deptid,@branchid,2,vipcardid,Comment
	FROM BakDly 
	WHERE Vchcode =@nVchcode AND PtypeID=''
	IF @@ROWCOUNT <>0  SET @INflag =1

	--库存商品     
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,dtypeid,branchid,billtype)
	VALUES  
	(@nVchcode,@tDate,@nVchType,@GOODS_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTempCostTotal,@period,'',@deptid,@branchid,2
	)  

	--应交税金增加  
	IF @dTempTaxtotal <> 0 
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,dtypeid,branchid,BillType)
	VALUES  
	(
	@nVchcode,@tDate,@nVchType,@TAX_ID,@szBtypeid,@szEtypeid,@szKtypeId,-@dtemptaxTotal,@period,'',@deptid,@branchid,2
	)  
	
	--销售收入  
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,dtypeid,branchid,BillType
	)
	VALUES  
	(
	@nVchcode,@tDate,@nVchType,@SALE_INCOME_ID,@szBtypeid,@szEtypeid,@szKtypeId,-@dTempTotal,@period,'',@deptid,@branchid,2
	)  
	
	--销售成本    
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,dtypeid,branchid,BillType)
	VALUES  
	(
	@nVchcode,@tDate,@nVchType,@SALE_COST_ID,@szBtypeid,@szEtypeid,@szKtypeId,-1 * @dTempCostTotal,@period,'',@deptid,@branchid,2
	)  
	   
	--应收应付  
	SET @dTotalInMoney =0 --收款金额
	IF 	@INflag =1
		SELECT @dTotalInMoney=sum(total) FROM BakDly WHERE Vchcode =@nVchcode AND PtypeID='' AND Usedtype =2
	SELECT  @dTemp = -@dTempTax_total - ( @dTotalInMoney + @dPreferential ) --应收 = 合计金额-（优惠金额+收款金额)  

	  
	IF  @procType = 'FZCS'
		EXEC FZUpdateYSYFTotal @dTemp, @szBtypeid, @nVchcode, @branchid,@nvchtype  

	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,dtypeid,branchid,BillType
	)
	VALUES  
	(
	@nVchcode,@tDate,@nVchType,@AR_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTemp,@period,'',@deptid,@branchid,2
	)  


	EXEC @nret=modifydbfNEW   'dlya',@nVchType,'',@nVchcode,@szktypeid,@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error
	--处理补货
	EXEC @nRet=GP_UpdatePtypeSupply @nVchcode,@nVchtype
	IF ( @@rowcount < 0 OR @@error <> 0) 
	BEGIN  
		SET @nRet = -2  
		GOTO error  
	END 
	----更改唯一码关联 Dlyorder			
	IF @procType = 'FZCS'
	BEGIN
            EXEC @nRet= GP_UpdatePtypeuniquecode  @nVchcode
			IF @nRet<>0
            GOTO error  
	END
	GOTO VIP
END
---销售换货单 END

--同价、变价调拔单
IF @nVchType IN ( 17,21 ) 
BEGIN
	--出库
	EXEC @nret=modifydbfNEW   'bakdly',@nVchType,'',@nVchcode,@szktypeid2,@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
	BEGIN
		select @szktypeid=@szktypeid2
		GOTO error
	END
	INSERT  INTO DlyData
	(
	vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,qty,price,total,costprice,costtotal,
	discount,discountprice,discounttotal,tax,taxprice,taxtotal,tax_total,comment,period,usedtype,costmode,
	unit,bargainTotal,colorid,Dtypeid,branchid,
	CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,BillType,RetailPrice,SaleMoney,vipcardid,OPID,PHROWS,UnitRate,SingleUnit
	)
	SELECT 
	@nVchcode,@tDate,@nVchType,@GOODS_ID,Ptypeid,@szBtypeid,@szEtypeid,@szKtypeId2,-Qty,
	case when @nvchtype =17 then round(CAST(costtotal/qty AS numeric(24,10)),@dig_price) else price end,
	case when @nvchtype =17 then -costTotal else -Total end,
	round(CAST(costtotal/qty AS numeric(24,10)),@dig_price),-costTotal,
	discount,discountprice,-discounttotal,tax,taxprice,-taxtotal,-tax_total,Comment,@period,usedtype,CostMode,
	unit,-bargaintotal,ColorID,@deptid,branchid,
	CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,3,RetailPrice,SaleMoney,VipCardID,OPID,PHROWS,UnitRate,SingleUnit
	FROM Bakdly where vchcode =@nVchCode AND Ptypeid<>'' --salemoney,bargaintotal本身为0，不用管正负号
	ORDER BY DlyOrder
	    IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  
	INSERT  INTO dlydatadetail
	(
	DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],DiscountTotal,CostTotal,salemoney,phrows,usedtype,vchcode
	)
	SELECT  a.DlyOrder,b.SIZEID,b.COLORID,-1 * b.QTY,
	case when @nvchtype =17 then round(-1 *CAST(cast(a.costtotal/a.qty as numeric(24,10)) * b.qty AS numeric(24,10)),@dig_total) else -1 * b.Total end,
	-1 * b.Taxtotal,-1 * b.Tax_total,-1 * b.BargainTotal,-1 * b.[Convert],-1 *b. DiscountTotal,
	round(-1 * CAST(cast(a.costtotal/a.qty as numeric(24,10))*b.qty AS numeric(24,10)),@dig_total),
	-1 * b.salemoney,a.phrows,a.usedtype,a.vchcode
	FROM    BakDlyDetail b ,dlydata a where a.Vchcode =@nVchcode AND b.Vchcode =@nVchcode 
			and a.phrows=b.phrows  AND a.Ptypeid<>''    AND a.ktypeid=@szKtypeId2
    IF  @@error <> 0 
    BEGIN  
        SET @nRet = -2  
        GOTO error  
    END  
	IF @nvchtype = 21 
	BEGIN
	    SELECT @bargainTotal = Sum(bargainTotal),@dTempCostTotal=Sum(costtotal)  FROM bakdly where  vchcode =@nVchcode AND ptypeid<>'' 
		update bakdly SET costmode= case when bargainTotal=0 then 4 else 0 end  where  vchcode =@nVchcode AND  ptypeid<>'' 
	END

 	--入库
 	EXEC @nret=modifydbfNEW   'bakdly',@nVchType,'',@nVchcode,@szktypeid,@szptypeid OUTPUT,-1,@OldVchcode
 	IF @nret<0
 		GOTO error

	INSERT  INTO DlyData
	(
	vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,qty,price,total,costprice,costtotal,
	discount,discountprice,discounttotal,tax,taxprice,taxtotal,tax_total,comment,period,usedtype,costmode,
	unit,bargainTotal,colorid,Dtypeid,branchid,
	CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,BillType,RetailPrice,SaleMoney,vipcardid,OPID,PHROWS,UnitRate,SingleUnit
	)
	SELECT 
	@nVchcode,@tDate,@nVchType,@GOODS_ID,Ptypeid,@szBtypeid,@szEtypeid,@szKtypeId,Qty,
	case when @nvchtype =17 then round(CAST(costtotal/qty AS numeric(24,10)),@dig_price) else price end,
	case when @nvchtype =17 then costtotal else Total end,
	round(CAST(case when @nvchtype =17 then costtotal else bargaintotal end/qty AS numeric(24,10)),@dig_price),
	case when @nvchtype =17 then costtotal else bargaintotal end,
	discount,discountprice,discounttotal,tax,taxprice,taxtotal,tax_total,Comment,@period,'',CostMode,
	unit,case when @nvchtype =17 then costtotal else bargaintotal end as bargaintotal,ColorID,@deptid,branchid,
	CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,3,RetailPrice,SaleMoney,VipCardID,OPID,PHROWS,UnitRate,SingleUnit
	FROM Bakdly where vchcode =@nVchCode AND Ptypeid<>'' --salemoney,bargaintotal本身为0，不用管正负号
    ORDER BY DlyOrder
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  
	
	INSERT  INTO dlydatadetail
	(
	DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],DiscountTotal,CostTotal,salemoney,phrows,usedtype,vchcode
	)
	SELECT  a.DlyOrder,b.SIZEID,b.COLORID, b.QTY,
	case when @nvchtype =17 then round( CAST(cast(a.costtotal/a.qty as numeric(24,10)) * b.qty AS NUMERIC(24,10)),@dig_total) else   b.Total end, 
	 b.Taxtotal,
	  b.Tax_total, round(CAST(cast(a.costtotal/a.qty as numeric(24,10)) * b.qty AS NUMERIC(24,10)),@dig_total) as BargainTotal,  
	  b.[Convert], b. DiscountTotal,
	  round(CAST(CAST(a.costtotal/a.qty as numeric(24,10)) * b.qty AS NUMERIC(24,10)),@dig_total) as costtotal, 
	  b.salemoney,a.phrows,a.usedtype,a.vchcode
	FROM    BakDlyDetail b ,dlydata a where a.Vchcode =@nVchcode AND b.Vchcode =@nVchcode and a.phrows=b.phrows  AND a.Ptypeid<>''  AND a.ktypeid=@szKtypeId
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  


	--分摊成本金额
	if exists(select 1 from dlydata a,(select sum(Costtotal) as Costtotal,sum(BargainTotal) as BargainTotal ,dlyorder from dlydatadetail where vchcode = @nVchcode   group by dlyorder)b 
               where a.vchcode = @nVchcode and a.dlyorder = b.dlyorder and (a.costtotal <> b.costtotal or a.BargainTotal <> b.BargainTotal))
		update dlydatadetail 
		set 
			costtotal = ff.costtotal+ (b.costtotal- a.costtotal)  ,
			BargainTotal = ff.BargainTotal+ (b.BargainTotal- a.BargainTotal)  
		from
			 (select vchcode,round(sum(costtotal),@dig_total) as costtotal,round(sum(BargainTotal),@dig_total) as BargainTotal, dlyorder from dlydatadetail where vchcode =@nVchcode  group by dlyorder,vchcode) a ,
			 dlydata b,dlydatadetail ff
		where
			b.vchcode =@nVchcode
			AND ff.vchcode =@nVchcode
			AND a.dlyorder=b.dlyorder and a.dlyorder = ff.dlyorder  and a.costtotal <> b.costtotal 
			and exists(
				select 1 from (select top 1 colorid,sizeid from dlydatadetail c where c.vchcode =@nVchcode AND ff.dlyorder = c.dlyorder order by colorid,sizeid) cc  where 
				ff.colorid = cc.colorid and ff.sizeid = cc.sizeid )

	IF @nvchtype = 21 
	BEGIN  
		--库存商品减少  
		INSERT  INTO dlya
		(
		vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype)
		VALUES  (@nVchcode,@tDate,@nVchType,@GOODS_ID,@szBtypeid,@szEtypeid,@szKtypeId2,-@dTempCostTotal,@period,'',@deptid,@branchid,3
		)  
		
		--库存商品增加  
		INSERT  INTO dlya
		(
		vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
		)
		VALUES  
		(
		@nVchcode,@tDate,@nVchType,@GOODS_ID,@szBtypeid,@szEtypeid,@szKtypeId,@bargainTotal,@period,'',@deptid,@branchid,3
		)  
	
	
		SELECT  @dTemp = @bargainTotal - @dTempcosttotal  
		IF @dTemp <> 0 
		BEGIN  
		INSERT  INTO dlya
		(
		vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@PRICEALLOT_CHANGE_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTemp,@period,'',@deptid,@branchid,3
		)  
		END  
	END  

	IF @nvchtype =17
      	SELECT @bargainTotal = Sum(CostTotal)  FROM bakdly where  vchcode =@nVchcode AND ptypeid<>'' 
	UPDATE  dlyndx	SET     Total = ABS(@bargainTotal)	WHERE   vchcode = @nVchcode 

	EXEC @nret=modifydbfNEW   'dlya',@nVchType,'',@nVchcode,@szktypeid,@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error
	
	----更改唯一码关联 Dlyorder			
	IF @procType = 'FZCS'
	BEGIN
            EXEC @nRet= GP_UpdatePtypeuniquecode  @nVchcode
			IF @nRet<>0
            GOTO error  
	END
	goto finish
END
	
IF @nVchType=16 --组装拆卸单
BEGIN
	--入库
	-- 0成本
	UPDATE bakdly SET Costmode = 4 WHERE Vchcode =@nVchcode AND PtypeID<>'' AND Total = 0 and usedtype=2
	EXEC @nret=modifydbfNEW  'bakdly',@nVchType,'',@nVchcode,@szktypeid,@szptypeid OUTPUT,2,@OldVchcode
	IF @nret<0
		GOTO error

	INSERT  INTO Dlydata
	(
	vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,qty,price,total,costprice,costtotal,
	discount,discountprice,discounttotal,tax,taxprice,taxtotal,tax_total,comment,period,usedtype,costmode,
	unit,bargainTotal,colorid,Dtypeid,branchid,CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,
	BillType,RetailPrice,SaleMoney,vipcardid,OPID,phrows,UnitRate,SingleUnit
	)
	SELECT 
	@nVchcode,@tDate,@nVchType,@GOODS_ID,Ptypeid,@szBtypeid,@szEtypeid,@szKtypeId,Qty,Price,Total,
	round(CAST(costtotal/qty AS NUMERIC(24,10)),@dig_price),costTotal,
	discount,discountprice,discountTotal,tax,taxprice,taxtotal,tax_total,comment,@period,usedtype,CostMode,
	unit,bargainTotal,ColorID,@deptid,branchid,CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,
	3,RetailPrice,SaleMoney,VipCardID,OPID,phrows,UnitRate,SingleUnit
	FROM Bakdly where vchcode =@nVchCode AND Ptypeid<>'' AND Usedtype =2
    ORDER BY DlyOrder
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  
		
	INSERT  INTO dlydatadetail
	(
	DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],DiscountTotal,CostTotal,salemoney,phrows,vchcode,usedtype
	)
	SELECT  a.DlyOrder,b.SIZEID,b.COLORID,b.QTY,
	round(cast(cast(a.costtotal/a.qty as numeric(24,10))* b.qty AS NUMERIC(24,10)),@dig_total),b.Taxtotal,
	round(cast(cast(a.costtotal/a.qty as numeric(24,10))* b.qty AS NUMERIC(24,10)),@dig_total),
	round(cast(cast(a.costtotal/a.qty as numeric(24,10))* b.qty AS NUMERIC(24,10)),@dig_total),b.[Convert],
	round(cast(cast(a.costtotal/a.qty as numeric(24,10))* b.qty AS NUMERIC(24,10)),@dig_total),
	round(cast(cast(a.costtotal/a.qty as numeric(24,10))* b.qty AS NUMERIC(24,10)),@dig_total),
	round(cast(cast(a.costtotal/a.qty as numeric(24,10))* b.qty AS NUMERIC(24,10)),@dig_total),a.phrows,a.vchcode,a.usedtype
	FROM    BakDlyDetail b ,dlydata a where a.Vchcode =@nVchcode AND a.vchcode =b.vchcode and a.phrows=b.phrows  and a.usedtype=2  and b.usedtype=2

    IF  @@error <> 0 
    BEGIN  
        SET @nRet = -2  
        GOTO error  
    END  
	--出库
	EXEC @nret=modifydbfNEW  'bakdly',@nVchType,'',@nVchcode,@szktypeid2,@szptypeid OUTPUT,1,@OldVchcode
	IF @nret<0
	BEGIN
		select @szktypeid=@szktypeid2
		GOTO error
	END
	INSERT  INTO Dlydata
	(
	vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,qty,price,total,costprice,costtotal,
	discount,discountprice,discounttotal,tax,taxprice,taxtotal,tax_total,comment,period,usedtype,costmode,
	unit,bargainTotal,colorid,Dtypeid,branchid,CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,
	BillType,RetailPrice,SaleMoney,vipcardid,OPID,phrows,UnitRate,SingleUnit
	)
	SELECT 
	@nVchcode,@tDate,@nVchType,@GOODS_ID,Ptypeid,@szBtypeid,@szEtypeid,@szKtypeId2,-Qty,
	round(CAST(costtotal/qty AS NUMERIC(24,10)),@dig_price),-Costtotal,
	round(CAST(costtotal/qty AS NUMERIC(24,10)),@dig_price),-costTotal,
	discount,
	round(CAST(costtotal/qty AS NUMERIC(24,10)),@dig_price),-Costtotal,tax,
	round(CAST(costtotal/qty AS NUMERIC(24,10)),@dig_price),taxtotal,-Costtotal,comment,@period,usedtype,CostMode,
	unit,-Costtotal,ColorID,@deptid,@branchid,CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,
	3,RetailPrice,SaleMoney,VipCardID,OPID,phrows,UnitRate,SingleUnit
	FROM Bakdly where vchcode =@nVchCode AND Ptypeid<>'' AND Usedtype =1
    ORDER BY DlyOrder
    IF  @@error <> 0 
    BEGIN  
        SET @nRet = -2  
        GOTO error  
    END  

	INSERT  INTO dlydatadetail
	(
	DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],DiscountTotal,CostTotal,salemoney,phrows,vchcode,usedtype
	)
	SELECT  a.DlyOrder,b.SIZEID,b.COLORID,-1 * b.QTY,
	round(cast(cast(a.costtotal/a.qty as numeric(24,10))* (-b.qty) AS NUMERIC(24,10)),@dig_total),-1 * b.Taxtotal,
	round(cast(cast(a.costtotal/a.qty as numeric(24,10))* (-b.qty) AS NUMERIC(24,10)),@dig_total),
	round(cast(cast(a.costtotal/a.qty as numeric(24,10))* (-b.qty) AS NUMERIC(24,10)),@dig_total),-1 * b.[Convert],
	round(cast(cast(a.costtotal/a.qty as numeric(24,10))* (-b.qty) AS NUMERIC(24,10)),@dig_total),
	round(cast(cast(a.costtotal/a.qty as numeric(24,10))* (-b.qty) AS NUMERIC(24,10)),@dig_total),
	round(cast(cast(a.costtotal/a.qty as numeric(24,10))* (-b.qty) AS NUMERIC(24,10)),@dig_total),a.phrows,a.vchcode,a.usedtype
	FROM    BakDlyDetail b ,dlydata a where a.Vchcode =@nVchcode AND a.vchcode =b.vchcode and a.phrows=b.phrows  and a.usedtype=1 and b.usedtype=1
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  

	--分摊成本金额
	if exists(select 1 from dlydata a,(select sum(Costtotal) as Costtotal,sum(BargainTotal) as BargainTotal,dlyorder from dlydatadetail where vchcode = @nVchcode   group by dlyorder)b 
               where a.vchcode = @nVchcode and a.dlyorder = b.dlyorder and (a.costtotal <> b.costtotal or a.BargainTotal <> b.BargainTotal))
		update dlydatadetail 
		set 
			costtotal = ff.costtotal+ (b.costtotal- a.costtotal)  ,
			BargainTotal = ff.BargainTotal+ (b.BargainTotal- a.BargainTotal)  
		from
			 (select vchcode,round(sum(costtotal),@dig_total) as costtotal,round(sum(BargainTotal),@dig_total) as BargainTotal, dlyorder from dlydatadetail where vchcode =@nVchcode  group by dlyorder,vchcode) a ,
			 dlydata b,dlydatadetail ff
		where
			b.vchcode =@nVchcode
			AND ff.vchcode =@nVchcode
			AND a.dlyorder=b.dlyorder and a.dlyorder = ff.dlyorder  and (a.costtotal <> b.costtotal or a.bargaintotal <> b.bargaintotal)
			and exists(
				select 1 from (select top 1 colorid,sizeid from dlydatadetail c where c.vchcode =@nVchcode AND ff.dlyorder = c.dlyorder order by colorid,sizeid) cc  where 
				ff.colorid = cc.colorid and ff.sizeid = cc.sizeid )


	select @dTempCostTotal=SUM(case when usedtype=1 then CostTotal else 0 end),@dTempTotal=SUM(case when usedtype=2 then total else 0 end) FROM Bakdly where vchcode =@nVchcode AND PtypeID<>''
	

	--库存商品减少  
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
	)
	VALUES  (
	@nVchcode,@tDate,@nVchType,@GOODS_ID,@szBtypeid,@szEtypeid,@szKtypeId,-@dTempCostTotal,@period,'',@deptid,@branchid,3
	)  
	--库存商品增加  
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
	)
	VALUES  (
	@nVchcode,@tDate,@nVchType,@GOODS_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTempTotal,@period,'',@deptid,@branchid,3
	)  
	
	--出库与入库成本差  
	SELECT  @dTemp = @dTemptotal - @dTempcosttotal  
	IF @dTemp <> 0 
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
	)
	VALUES  (
	@nVchcode,@tDate,@nVchType,@GOODS_PRODUCE_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTemp,@period,'',@deptid,@branchid,3
	)  
	
	EXEC @nret=modifydbfNEW  'dlya',@nVchType,'',@nVchcode,@szktypeid,@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error


	UPDATE  dlyndx
	SET     BillType = 3,total =abs(@dTempCostTotal)
	WHERE   vchcode = @nVchcode  
	IF @procType = 'FZCS'
	BEGIN
            EXEC @nRet= GP_UpdatePtypeuniquecode  @nVchcode
			IF @nRet<>0
            GOTO error  
	END
	GOTO finish
END

IF @nVchType = 150 	 ---明细调整单开始  
BEGIN
	EXEC @nret=modifydbfNEW  'bakdly',@nVchType,'',@nVchcode,@szktypeid,@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error
	INSERT  INTO Dlydata
	(
	vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,qty,price,total,costprice,costtotal,
	discount,discountprice,discounttotal,tax,taxprice,taxtotal,tax_total,comment,period,usedtype,costmode,
	unit,colorid,bargainTotal,branchid,Dtypeid,CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,
	BillType,RetailPrice,SaleMoney,vipcardid,OPID,phrows,UnitRate,SingleUnit
	)
	SELECT 
	@nVchcode,@tDate,@nVchType,@GOODS_ID,Ptypeid,@szBtypeid,@szEtypeid,@szKtypeId,0,costtotal,0 as total,
	costtotal,0,discount,discountprice,0,tax,taxprice,taxtotal,tax_total,comment,@period,usedtype,CostMode,
	unit,ColorID,bargainTotal,branchid,@deptid,CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,3 as billtype,RetailPrice,SaleMoney,VipCardID,OPID,phrows,UnitRate,SingleUnit
	FROM BakDly WHERE Vchcode =@nVchcode AND PtypeID<>''
	ORDER BY DlyOrder
    IF  @@error <> 0 
    BEGIN  
        SET @nRet = -2  
        GOTO error  
    END  

	INSERT  INTO dlydatadetail
	(
	DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],DiscountTotal,CostTotal,salemoney,phrows,usedtype,vchcode
	)
	SELECT  a.DlyOrder,b.SIZEID,b.COLORID,b.QTY,b.Total,b.Taxtotal,b.Tax_total,b.BargainTotal,b.[Convert],b.DiscountTotal,round(b.costtotal,@dig_total),b.salemoney,a.phrows,a.usedtype,a.vchcode
	FROM    BakDlyDetail b ,dlydata a where a.Vchcode =@nVchcode AND a.vchcode =b.vchcode and a.phrows=b.phrows 
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  

	----更改唯一码关联 Dlyorder			
	IF @procType = 'FZCS'
	BEGIN
            EXEC @nRet= GP_UpdatePtypeuniquecode  @nVchcode
			IF @nRet<>0
            GOTO error  	
	END

	IF @nret<0
		GOTO error

	goto finish
END
	
IF @nVchType = 57 	 ---成本调整单开始  
BEGIN
	--无库存，不能做成本调整单
        if exists(select 1  from bakdly b left join(select qty,ptypeid from goodsstocks where ktypeid = @szktypeid) g
                  on b.ptypeid = g.ptypeid where b.vchcode=@nVchcode   and b.ptypeid<>'' and isnull(g.qty,0) = 0)
        begin
 		SET @nRet = -918  
 		SET @szptypeid=''
                select @szptypeid =  @szptypeid + ptypeid +',',@szktypeid = ktypeid from 
                 (select distinct b.ptypeid,b.ktypeid from  bakdly b left join(select qty,ptypeid from goodsstocks where ktypeid = @szktypeid) g
                  on b.ptypeid = g.ptypeid where b.vchcode=@nVchcode   and b.ptypeid<>'' and isnull(g.qty,0) = 0)ls
 		GOTO error           
        end
-- 	--无库存，不能做成本调整单
-- 	IF NOT EXISTS ( SELECT  1 FROM    goodsstocks g ,bakdly b WHERE b.vchcode=@nVchcode and g.ktypeid=@szktypeid  and b.ptypeid<>'' and g.ptypeid=b.ptypeid ) 
-- 	BEGIN  
-- 		SET @nRet = -918  
-- 		SET @szptypeid=''
-- 		select @szptypeid =  @szptypeid + ptypeid +',',@szktypeid = ktypeid from  (select distinct ptypeid,ktypeid from bakdly a  where   vchcode = @nVchCode and ptypeid <> '' and not exists (select * from Goodsstocks g where g.ktypeid=@szktypeid  and g.ptypeid=a.ptypeid)) ls
-- 		GOTO error  
-- 	END  
	--成本异常时，不能做成本调整单  --modify by 老罗 判断成本异常需要goodsstocks的二级明细表2012-08-29
    IF EXISTS ( SELECT  1
                FROM    goodsstocks g ,
                        bakdly b
                WHERE   b.vchcode = @nVchcode
                        AND g.ktypeid = @szktypeid
                        AND b.ptypeid <> ''
                        AND g.ptypeid = b.ptypeid
                        AND ((g.qty>0 AND g.Total<0)
							  OR
							 (g.qty<0 AND g.Total>0)
							 )
                                             	 --总量成本异常
			 )
	--OR EXISTS(SELECT    1
 --             FROM      goodsstocks g ,
 --                       goodsstockdetail gd ,
 --                       bakdly b
 --             WHERE     g.orderid = gd.orderid
 --                       AND b.vchcode = @nVchcode
 --                       AND g.ktypeid = @szktypeid
 --                       AND b.ptypeid <> ''
 --                       AND g.ptypeid = b.ptypeid
 --                       AND gd.Total<0 
 --                       AND g.Total>0
 --             )		 
        
    OR EXISTS (SELECT    1
              FROM      goodsstocks g ,
                        goodsstockdetail gd ,
                        bakdly b
              WHERE     g.orderid = gd.orderid
                        AND b.vchcode = @nVchcode
                        AND g.ktypeid = @szktypeid
                        AND b.ptypeid <> ''
                        AND g.ptypeid = b.ptypeid
                        AND ((gd.qty>0 AND gd.Total<0)
							  OR
							 (gd.qty<0 AND gd.Total>0)
							 )    --明细成本异常
                         
               ) --总量成本异常
        BEGIN  
            SET @nRet = -919  
            SET @szptypeid = ''
            SELECT  @szptypeid = @szptypeid + g.ptypeid + ','  --总量
                    
            FROM    goodsstocks g ,
                    bakdly b
            WHERE   b.vchcode = @nVchcode
                        AND g.ktypeid = @szktypeid
                        AND b.ptypeid <> ''
                        AND g.ptypeid = b.ptypeid
                        AND ((g.qty>0 AND g.Total<0)
							  OR
							 (g.qty<0 AND g.Total>0)
							 )
                        
            IF @szptypeid=''
            BEGIN
				  SELECT  @szptypeid = @szptypeid + g.ptypeid + ',' --明细正负号
                     
		          FROM      goodsstocks g ,
                            goodsstockdetail gd ,
                            bakdly b
                  WHERE     g.orderid = gd.orderid
                            AND b.vchcode = @nVchcode
                            AND g.ktypeid = @szktypeid
                            AND b.ptypeid <> ''
                            AND g.ptypeid = b.ptypeid
                            AND ((gd.qty>0 AND gd.Total<0)
							  OR
								(gd.qty<0 AND gd.Total>0)
								)   
            END
      --      IF @szptypeid=''
      --      BEGIN
				  --SELECT  @szptypeid = @szptypeid + g.ptypeid + ',' --明细金额为负
                     
		    --      FROM      goodsstocks g ,
      --                      goodsstockdetail gd ,
      --                      bakdly b
      --            WHERE     g.orderid = gd.orderid
      --                      AND b.vchcode = @nVchcode
      --                      AND g.ktypeid = @szktypeid
      --                      AND b.ptypeid <> ''
      --                      AND g.ptypeid = b.ptypeid
      --                      AND gd.Total<0 
      --                      AND g.Total>0
      --      END
            GOTO error  
        END  
    IF EXISTS ( SELECT  *
                FROM    ( SELECT    g.ptypeid ,
                                    SUM(ISNULL(g.qty, 0)) AS qty
                          FROM      goodsstocks g ,
                                    bakdly b
                          WHERE     b.vchcode = @nVchcode
                                    AND g.ktypeid = @szktypeid
                                    AND b.ptypeid <> ''
                                    AND g.ptypeid = b.ptypeid
                          GROUP BY  g.ptypeid
                        ) x
                WHERE   x.qty = 0 ) 
        BEGIN  
            SET @nRet = -911  
            SET @szptypeid = ''
            SELECT  @szptypeid = @szptypeid + ptypeid + ','
            FROM    ( SELECT    g.ptypeid ,
                                SUM(ISNULL(g.qty, 0)) AS qty
                      FROM      goodsstocks g ,
                                bakdly b
                      WHERE     b.vchcode = @nVchcode
                                AND g.ktypeid = @szktypeid
                                AND b.ptypeid <> ''
                                AND g.ptypeid = b.ptypeid
                      GROUP BY  g.ptypeid
                    ) x
            WHERE   x.qty = 0
            GOTO error  
        END  
	
	--出库
	INSERT  INTO dlydata
	(
	vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,qty,price,total,
	costprice,costtotal,discount,discountprice,discounttotal,tax,taxprice,taxtotal,tax_total,
	comment,period,usedtype,costmode,unit,bargainTotal,colorid,[convert],Dtypeid,BranchId,
	CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,BillType,RetailPrice,
	SaleMoney,vipcardid,OPID,phrows,UnitRate,SingleUnit
	)
	SELECT
		@nVchcode,@tDate,@nVchType,@GOODS_ID,a.Ptypeid,@szBtypeid,@szEtypeid,@szKtypeId,
		-a.Qty,b.price,round(CAST(-a.qty*b.price AS NUMERIC(24,10)),@dig_total),
		round(CAST(a.total/(case when a.qty =0 then 1 else a.qty end) AS NUMERIC(24,10)),@dig_price),
		-a.Total,b.discount,b.price,-a.total,
		b.tax,b.price,-b.taxtotal,-b.tax_total,b.comment,@period,b.usedtype,b.CostMode,
		b.unit,-a.Total,b.ColorID,b.[convert],@deptid,b.branchid,b.CustValue1,b.CustValue2,b.CustValue3,b.CustValue4,b.CustValue5,b.CustValue6,
		3,b.RetailPrice,-b.SaleMoney,b.VipCardID,b.OPID,b.phrows,b.UnitRate,b.SingleUnit
	FROM Goodsstocks a,BakDly b WHERE b.Vchcode =@nVchcode AND b.PtypeID<>'' and a.ktypeid=b.ktypeid and a.ptypeid=b.ptypeid
	ORDER BY b.DlyOrder
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  
	
	select @dTempCostTotal =SUM(Costtotal) FROM Dlydata where  Vchcode =@nVchcode
	
	INSERT  INTO dlydataDetail
	(
	DlyOrder,SIZEID,COLORID,QTY,costTotal,usedtype,phrows,vchcode
	)
	SELECT  c.DlyOrder,a.SIZEID,a.COLORID,
		-1 * round(SUM(a.QTY),@dig_qty),-1 *round(SUM(a.Total),@dig_total),c.usedtype,c.phrows,c.vchcode
	FROM    Goodsstockdetail a,Goodsstocks b,dlydata c
	where b.ktypeid=@szktypeid and c.vchcode =@nVchcode AND a.orderid=b.orderid 
		and c.ktypeid=@szktypeid and b.ktypeid =@szktypeid and c.ktypeid=b.ktypeid 
		and c.ptypeid=b.ptypeid and c.usedtype=1
	GROUP BY a.sizeid,a.colorid,c.dlyorder,c.usedtype,c.phrows,c.vchcode
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  

	--入库 '' as usedtype
	INSERT  INTO dlydata
	(
	vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,qty,price,total,
	costprice,costtotal,discount,discountprice,discounttotal,tax,taxprice,taxtotal,tax_total,
	comment,period,usedtype,costmode,unit,bargainTotal,colorid,[convert],Dtypeid,BranchId,
	CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,BillType,RetailPrice,
	SaleMoney,vipcardid,OPID,Phrows,UnitRate,SingleUnit
	)
	SELECT
		@nVchcode,@tDate,@nVchType,@GOODS_ID,a.Ptypeid,@szBtypeid,@szEtypeid,@szKtypeId,
		a.Qty,b.price,round(CAST(a.qty*b.price AS NUMERIC(24,10)),@dig_total),b.price,
		round(CAST(a.qty*b.price AS NUMERIC(24,10)),@dig_total),b.discount,b.price,
		round(CAST(a.qty*b.price AS NUMERIC(24,10)),@dig_total),
		b.tax,b.price,0 as taxtotal,0 as tax_total,b.comment,@period,'' as usedtype,b.CostMode,
		b.unit,
		round(CAST(a.qty*b.price AS NUMERIC(24,10)),@dig_total),b.ColorID,b.[convert],@deptid,b.branchid,b.CustValue1,
		b.CustValue2,b.CustValue3,b.CustValue4,b.CustValue5,b.CustValue6,
		3,b.RetailPrice,0 as SaleMoney,b.VipCardID,b.OPID,b.phrows,b.UnitRate,b.SingleUnit
	FROM Goodsstocks a,BakDly b WHERE b.Vchcode =@nVchcode AND b.PtypeID<>'' and a.ktypeid=b.ktypeid and a.ptypeid=b.ptypeid 
	ORDER BY b.DlyOrder
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  
	
	select @dTemptotal =SUM(Costtotal) FROM Dlydata where  Vchcode =@nVchcode and usedtype=''
	
	INSERT  INTO dlydataDetail
	(
	DlyOrder,SIZEID,COLORID,QTY,costTotal,usedtype,phrows,vchcode
	)
	SELECT  c.DlyOrder,a.SIZEID,a.COLORID, round(SUM(a.QTY),@dig_qty), 
	round(CAST(SUM(a.qty*c.price) AS NUMERIC(24,10)),@dig_total),'' as usedtype,c.phrows,c.vchcode
	FROM    Goodsstockdetail a,Goodsstocks b,dlydata c
	where b.ktypeid=@szktypeid and c.vchcode =@nVchcode AND a.orderid=b.orderid 
		and c.ktypeid=@szktypeid and b.ktypeid =@szktypeid and c.ktypeid=b.ktypeid and c.ptypeid=b.ptypeid and c.usedtype='' 
	GROUP BY a.sizeid,a.colorid,c.dlyorder,c.phrows,c.vchcode 
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  

	--分摊成本金额
	if exists(select  1 from dlydata a,(select sum(Costtotal) as Costtotal,sum(total) as total,dlyorder from dlydatadetail where vchcode = @nVchcode   group by dlyorder)b 
               where a.vchcode = @nVchcode and a.dlyorder = b.dlyorder and (a.costtotal <> b.costtotal or a.total <> b.total))
		update dlydatadetail 
		set 
			costtotal = ff.costtotal+ (b.costtotal- a.costtotal),  
                        total = ff.total+ (b.total- a.total)  
		from
			 (select vchcode,round(sum(costtotal),@dig_total) as costtotal,round(sum(total),@dig_total) as total, dlyorder from dlydatadetail where vchcode =@nVchcode  group by dlyorder,vchcode) a ,
			 dlydata b,dlydatadetail ff
		where
			b.vchcode =@nVchcode
			AND ff.vchcode =@nVchcode
			AND a.dlyorder=b.dlyorder and a.dlyorder = ff.dlyorder  and (a.costtotal <> b.costtotal or a.total <> b.total)
			and exists(
				select 1 from (select top 1 colorid,sizeid from dlydatadetail c where c.vchcode =@nVchcode AND ff.dlyorder = c.dlyorder order by colorid,sizeid) cc  where 
				ff.colorid = cc.colorid and ff.sizeid = cc.sizeid )

	


	--库存处理,相当于modifydbfnew
	UPDATE  Goodsstocks
		SET Total = round(CAST((case when a.qty=0 then 1 else a.qty end)*b.price AS NUMERIC(24,10)),@dig_total),
	        price = b.price
	FROM Goodsstocks a INNER JOIN bakdly b on a.ktypeid=b.ktypeid and a.ptypeid=b.ptypeid
	where b.vchcode =@nVchcode
		and a.ktypeid=@szktypeid
    IF  @@error <> 0 
    BEGIN  
        SET @nRet = -2  
        GOTO error  
    END  

	UPDATE  Goodsstockdetail
	SET     Total = round(c.price * a.qty,@dig_total)
	FROM 
	Goodsstockdetail a,Goodsstocks b,bakdly c
	where c.vchcode =@nVchcode AND a.orderid=b.orderid and c.ktypeid=@szktypeid 
		and b.ktypeid =@szktypeid and c.ktypeid=b.ktypeid and c.ptypeid=b.ptypeid
    IF  @@error <> 0 
    BEGIN  
        SET @nRet = -2  
        GOTO error  
    END  
	
     if exists(select 1 from goodsstocks a,(select sum(total) as total, orderid from GoodsStockDetail  group by orderid)b where a.orderid = b.orderid and a.total <> b.total
               and exists(select 1 from bakdly x where x.vchcode = @nVchcode and a.ktypeid=@szKtypeId and  x.ktypeid = a.ktypeid and x.ptypeid = a.ptypeid )) 
	update GoodsStockDetail 
	set total = ff.total+ (b.total- a.total)  
	from (select round(sum(total),@dig_total) as total, orderid 
             from GoodsStockDetail  group by orderid) a  , goodsstocks b
             ,GoodsStockDetail ff
	where a.orderid=b.orderid and a.orderid = ff.orderid  and a.total <> b.total 
        and exists(select 1 from bakdly x where x.vchcode = @nVchcode and  x.ktypeid = b.ktypeid and x.ptypeid = b.ptypeid ) 
        and exists
           (select 1 from (select top 1 orderid,colorid,sizeid from GoodsStockDetail c where ff.orderid = c.orderid order by colorid,sizeid) cc  where 
                    ff.colorid = cc.colorid and ff.sizeid = cc.sizeid  and ff.orderid = cc.orderid)
            IF  @@error <> 0 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  

	--库存商品减少  
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,branchid,Dtypeid,billtype)
	VALUES  (@nVchcode,@tDate,@nVchType,@GOODS_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTempCostTotal,@period,'',@branchid,@deptid,3
	)  
	
	--库存商品增加  
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,branchid,Dtypeid,billtype
	)
	VALUES  (
	@nVchcode,@tDate,@nVchType,@GOODS_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTempTotal,@period,'',@branchid,@deptid,3
	)  
		--调价收入  
	
	SELECT  @dTemp = @dTemptotal + @dTempcosttotal  
	IF @dTemp <> 0 
	BEGIN  
		INSERT  INTO dlya
		(
		vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,branchid,Dtypeid,billtype
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@ALLOT_INCOME_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTemp,@period,'',@branchid,@deptid,3
		)  
	END

	EXEC @nret=modifydbfNEW   'dlya',@nVchType,'',@nVchcode,'',@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error
	----更改唯一码关联 Dlyorder			
	IF @procType = 'FZCS'
	BEGIN
            EXEC @nRet= GP_UpdatePtypeuniquecode  @nVchcode
			IF @nRet<>0
            GOTO error  	
	END

	IF @nret<0
		GOTO error

	goto finish

END
	
		
IF @nVchType IN ( 9, 14, 126, 139, 140, 141, 142, 143 ) ---报损、报溢、获赠单、赠送开始 
BEGIN
	EXEC @nret=modifydbfNEW  'bakdly',@nVchType,'',@nVchcode,@szktypeid,@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error
	IF @nVchType IN ( 9, 139, 140, 143 ) 
		SELECT  @SIGN = -1  
	INSERT  INTO dlydata
	(
	vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,qty,price,total,costprice,costtotal,
	discount,discountprice,discounttotal,tax,taxprice,taxtotal,tax_total,comment,period,usedtype,costmode,
	unit,colorid,bargainTotal,branchid,Dtypeid,CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,
	BillType,RetailPrice,SaleMoney,vipcardid,OPID,phrows,UnitRate,SingleUnit
	)
	SELECT 
	@nVchcode,@tDate,@nVchType,@GOODS_ID,Ptypeid,@szBtypeid,@szEtypeid,@szKtypeId,@SIGN*Qty,
	round(CAST(costtotal/qty AS NUMERIC(24,10)),@dig_price),@SIGN*CostTotal,
	round(CAST(costtotal/qty AS NUMERIC(24,10)),@dig_price),@SIGN*costTotal,discount,discountprice,
	@SIGN*Costtotal,tax,taxprice,taxtotal,tax_total,comment,
	@period,usedtype,CostMode,unit,ColorID,bargainTotal,@branchid,@deptid,CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,
	CASE WHEN @nVchType IN ( 9, 14, 126, 139 ) THEN 3 ELSE 5 END,RetailPrice,SaleMoney,VipCardID,OPID,phrows,UnitRate,SingleUnit
	FROM BakDly WHERE Vchcode =@nVchcode AND PtypeID<>''
	ORDER BY DlyOrder
	INSERT  INTO dlydatadetail
	(
	vchcode,DlyOrder,usedtype,phrows,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],DiscountTotal,CostTotal,salemoney
	)
	SELECT  a.vchcode,a.DlyOrder,a.usedtype,a.phrows,b.SIZEID,b.COLORID,round(@sign * b.QTY,@dig_qty),round(@sign * b.Total,@dig_total),round(@sign* b.Taxtotal,@dig_total),
	round(@sign* b.Tax_total,@dig_total),round(@sign* b.BargainTotal,@dig_total),round(@sign* b.[Convert],@dig_total),round(@sign* b.DiscountTotal,@dig_total),
	round(CAST(@sign * b.qty* a.costtotal/a.qty AS NUMERIC(24,10)),@dig_total),
	round(@sign* b.salemoney,@dig_total)
	FROM    BakDlyDetail b ,dlydata a where a.Vchcode =@nVchcode AND a.vchcode =b.vchcode and a.phrows=b.phrows 

	--分摊成本金额
	if exists(select  1 from dlydata a,(select sum(Costtotal) as Costtotal,dlyorder from dlydatadetail where vchcode = @nVchcode   group by dlyorder)b 
               where a.vchcode = @nVchcode and a.dlyorder = b.dlyorder and a.costtotal <> b.costtotal)
		update dlydatadetail 
		set 
			costtotal = ff.costtotal+ (b.costtotal- a.costtotal)  
		from
			 (select vchcode,round(sum(costtotal),@dig_total) as costtotal, dlyorder from dlydatadetail where vchcode =@nVchcode  group by dlyorder,vchcode) a ,
			 dlydata b,dlydatadetail ff
		where
			b.vchcode =@nVchcode
			AND ff.vchcode =@nVchcode
			AND a.dlyorder=b.dlyorder and a.dlyorder = ff.dlyorder  and a.costtotal <> b.costtotal 
			and exists(
				select 1 from (select top 1 colorid,sizeid from dlydatadetail c where c.vchcode =@nVchcode AND ff.dlyorder = c.dlyorder order by colorid,sizeid) cc  where 
				ff.colorid = cc.colorid and ff.sizeid = cc.sizeid )



	SELECT @dTempCostTotal=SUM(costtotal) FROM BakDly WHERE Vchcode =@nVchcode AND PtypeID<>''
	
	IF @nVchtype IN ( 9, 14, 126, 139 )
		SET @billtype =3
	ELSE
		SET @billtype =5
	IF @nVchtype = 9  --报损
	BEGIN
		SET @szAtypeid=@GOODS_LOSS_ID
		SET @dTempCostTotal =-@dTempCostTotal
	END
	IF @nVchtype = 14 --报溢
	BEGIN
		SET @szAtypeid=@GOODS_GET_ID
	END
	IF @nVchtype = 126 --获赠单
	BEGIN
		SET @szAtypeid=@GOODS_GIVEME_ID
	END
	IF @nVchtype = 139 --赠送
	BEGIN
		SET @szAtypeid=@GOODS_GIVE_ID
		SET @dTempCostTotal =-@dTempCostTotal
	END

	--库存商品变化  
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,branchid,Dtypeid,billtype
	)
	VALUES  (
	@nVchcode,@tDate,@nVchType,@GOODS_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTempCostTotal,@period,'',@branchid,@deptid,@billtype
	)
	
	--科目变化  
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,branchid,Dtypeid,billtype
	)
	VALUES  (
	@nVchcode,@tDate,@nVchType,@szAtypeid,@szBtypeid,@szEtypeid,@szKtypeId,ABS(@dTempCostTotal),@period,'',@branchid,@deptid,@billtype
	)  
	EXEC @nret=modifydbfNEW  'dlya',@nVchType,'',@nVchcode,@szktypeid,@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error

  	-- 改变盘点单的状态   
	IF  @nVchType IN ( 9, 14)
    BEGIN   
        DECLARE @tmpCode INT  
        DECLARE @PdKtypeId VARCHAR(50)  
        SELECT  @tmpCode = CONVERT(INT, ExpandId),@PdKtypeId = KtypeId FROM    dlyndx WHERE   vchcode = @nVchcode  
        IF @tmpCode > 0 
        BEGIN              
			-- 老版本由于上下传，可能存在异地报损报溢单都集中在一个帐套的情况，故可能存在一个vchcode对应错误。故还要增加仓库Id相同的控制  
   			-- 此处增加<>2为了减少快照复制后过账导致已过账的盘点单被重复改写  
			IF @nVchType =9
            	UPDATE  dlyndxChecked SET     draft = 2 WHERE   vchcode1 = @tmpCode  AND KtypeId = @PdKtypeId AND @nVchType = 9 AND draft <> 2   
			IF @nVchType =14
                UPDATE  dlyndxChecked   SET     draft = 2   WHERE   vchcode2 = @tmpCode AND KtypeId = @PdKtypeId AND @nVchType = 14 AND draft <> 2   
            UPDATE  dlyndx  SET     ExpandId = '' WHERE   vchcode = @PDVchCode  
        END  
    END  
	----更改唯一码关联 Dlyorder			
	IF @procType = 'FZCS'
	BEGIN
            EXEC @nRet= GP_UpdatePtypeuniquecode  @nVchcode
			IF @nRet<>0
            GOTO error  
	END
	goto VIP
END



--钱流
IF @nVchType IN ( 36, 35, 84, 10, 93, 85, 78, 5, 77 ) 
BEGIN --一般费用单、现金费用单、固定资产购置、待摊费用摊销、其它收入单、固定资产变卖 拆旧、待摊费用发生   
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,Comment,total,period,usedtype,Dtypeid,branchid,BillType
	)
	SELECT
	@nVchcode,@tDate,@nVchType,Atypeid,@szBtypeid,@szEtypeid,@szKtypeId,Comment,
	case when usedtype=1 AND @nVchType IN ( 85, 78, 5 )   THEN -Total when usedtype=2 AND @nVchType NOT IN ( 93, 85, 78, 5 )    THEN -Total else total end as total,
	@period,Usedtype,@deptid,branchid,6
	FROM bakdly where vchcode =	@nVchcode AND Total<>0
    ORDER BY DlyOrder
	SELECT @dTempTotal=SUM(total) FROM bakdly where vchcode =@nVchcode AND Usedtype=1 AND Total<>0 
	SELECT @dTotalInMoney=ISNULL(SUM(total),0) FROM bakdly where vchcode =@nVchcode AND Usedtype=2 AND Total<>0 

	IF ( @nVchtype = 78 )   --拆旧  
	BEGIN  
		INSERT  INTO dlya ----固定资产折旧  
		(
		vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
		)
		SELECT @nVchcode,@tDate,@nVchType,@FIXED_REDUCE_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTempTotal,@period,'',@deptid,@branchid, 6
	
	END  
	IF @nVchType = 77
	BEGIN
		SELECT @branchidT3 =branchid FROM bakdly where vchcode =@nVchcode AND Usedtype=2 AND Total<>0
		IF  @branchidT3 <> @branchidT --内部转款单不同机构之间的转款（涉及到内部结算单）
		BEGIN
			INSERT  INTO dlya
			(
			vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
			)
			VALUES  (
			@nVchcode,@tDate,@nVchType,'0000100009',@szBtypeid,@szEtypeid,@szKtypeId,-@dTempTotal,@period,'',@deptid,@branchidT,6
			)
			
			INSERT  INTO dlya
			(
			vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
			)
			VALUES  
			(
			@nVchcode,@tDate,@nVchType,'0000100009',@szBtypeid,@szEtypeid,@szKtypeId,@dTempTotal,@period,'',@deptid,@branchidT3,6
			)
		END
	END
	IF @nVchType IN ( 36, 35, 84, 10, 93 ) 
	BEGIN  
		SET @YSYFTotal = -1 * ( @dTempTotal - @dTotalInMoney )  
	END  
	ELSE 
		SET @YSYFTotal = ( @dTempTotal - @dTotalInMoney )  
	IF @nvchtype = 93 
		SET @YSYFTotal = -@YSYFTotal  
	
	UPDATE  dlyndx SET     Total = ABS(@dTempTotal),billtype = 6 WHERE   vchcode = @nVchcode  
	
	IF @nVchType <> 77  AND  @procType = 'FZCS'
		EXEC FZUpdateYSYFTotal @YSYFTotal, @szBtypeid, @nVchcode,@branchid,@nvchtype  

	IF ( @dTotalInMoney <> @dTempTotal ) AND ( @nVchtype NOT IN ( 10, 77, 78, 5 ) ) 
	BEGIN  
		INSERT  INTO dlya
		(
		vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,CASE WHEN @nvchtype IN ( 36, 35, 84, 10 )THEN @AP_ID ELSE @AR_ID END,
		@szBtypeid,@szEtypeid,@szKtypeId,@dTempTotal - @dTotalInMoney,@period,'',@deptid,@branchid,6
		)  
	END    
	
	EXEC @nret=modifydbfNEW   'dlya',@nVchType,'',@nVchcode,'',@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error
    goto finish 
END  

------------------------------收款单  
IF @nVchType IN ( 4, 66 ) 
BEGIN
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,Comment,total,period,usedtype,Dtypeid,branchid,BillType
	)
	SELECT 
		@nVchcode,@tDate,@nVchType,Atypeid,@szBtypeid,@szEtypeid,@szKtypeId,Comment,
		CASE WHEN @nvchtype = 4 AND ATypeID <>'0000200888' THEN  Total ELSE -1 * Total END,
		@period,Usedtype,@deptid,branchid,6
	FROM bakdly where vchcode =@nVchcode AND Usedtype=1 AND Total<>0 
	ORDER BY DlyOrder
	
	SELECT @dTempTotal=SUM(total) FROM bakdly where vchcode =@nVchcode AND Usedtype=1 AND Total<>0 

	IF @PHID =5  --收款4，只能是客户  (--用于保存单据业务类型 1配货、2退货、3调配 4销售收款、5预收账款、6其他收款 7采购付款、8预付账款、9其他付款)
	BEGIN
		UPDATE  dlyndx SET     Total = (@dTempTotal),billtype = 6 WHERE   vchcode = @nVchcode  
		 --预收
		INSERT  INTO dlya
		(
		vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,'0000200888',@szBtypeid,@szEtypeid,@szKtypeId,@dTempTotal,@period,'',@deptid,@branchid,6
		)  
	END 
	ELSE IF  @PHID =8  --付款66,只能是供应商
	BEGIN
		UPDATE  dlyndx SET     Total = (@dTempTotal),billtype = 6 WHERE   vchcode = @nVchcode  
		 --预付
		INSERT  INTO dlya
		(
		vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,'0000100888',@szBtypeid,@szEtypeid,@szKtypeId,@dTempTotal,@period,'',@deptid,@branchid,6
		)  
	END
	ELSE  --应付款增加（供应商，加盟商供应商【总部机构对应往来单位】）  
	BEGIN
		IF LEFT(@szBtypeid, 5) = '00001'  OR LEFT(@szBtypeid, 5) = '00007'  
		BEGIN  
			UPDATE  dlyndx SET     Total = (@dTempTotal),billtype = 6 WHERE   vchcode = @nVchcode  
			SET @dTempTotal = CASE WHEN @nvchtype = 4 THEN @dTempTotal   ELSE -1 * @dTempTotal END  
			IF @procType = 'FZCS'
				EXEC FZUpdateYSYFTotal @dTempTotal, @szBtypeid, @nVchcode,@branchid,@nvchtype 
			INSERT  INTO dlya
			(
			vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
			)
			VALUES  (
			@nVchcode,@tDate,@nVchType,@AP_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTempTotal,@period,'',@deptid,@branchid,6
			)  
		END  
		--应收款减少（一般客户）     
		IF LEFT(@szBtypeid, 5) NOT IN ('00001','00007')
		BEGIN  
			UPDATE  dlyndx SET     Total = (@dTempTotal),billtype = 6 WHERE   vchcode = @nVchcode  
			SET @dTempTotal = CASE WHEN @nvchtype = 4   THEN -1 * @dTempTotal   ELSE @dTempTotal END  
			IF @procType = 'FZCS'
				EXEC FZUpdateYSYFTotal @dTempTotal, @szBtypeid, @nVchcode,@branchid,@nvchtype  
			INSERT  INTO dlya
			(
			vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
			)
			VALUES  (
			@nVchcode,@tDate,@nVchType,@AR_ID,@szBtypeid,@szEtypeid,@szKtypeId,@dTempTotal,@period,'',@deptid,@branchid,6
			)  
		END  
	END
	EXEC @nret=modifydbfNEW   'dlya',@nVchType,'',@nVchcode,'',@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error
    goto finish  
END

------------------------------------往来核销单
IF @nVchType=253
BEGIN	
	--获得单据总核销金额
	 DECLARE @v253_total NUMERIC(24, 10)
	 SELECT @v253_total=Total FROM dbo.DlyNdx WHERE  vchcode =@nVchcode 
	--判断核销类型下的子类型 应收冲应收 应付冲应付  应收冲应付
	IF  @PHID=10 --应收冲应收
	BEGIN
		INSERT  INTO dlya --转出客户 应收减少
		(
		vchcode,[Date],vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@AR_ID,@szBtypeid2,@szEtypeid,@szKtypeId,-1*@v253_total,@period,'',@deptid,@branchid,6
		)  
		
		INSERT  INTO dlya --转入客户 应收增加
		(
		vchcode,[Date],vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@AR_ID,@szBtypeid,@szEtypeid,@szKtypeId,1*@v253_total,@period,'',@deptid,@branchid,6
		) 
	END
	ELSE IF @PHID=11 --应付冲应付
	BEGIN
		INSERT  INTO dlya --转出客户 应付减少
		(
		vchcode,[Date],vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@AP_ID,@szBtypeid2,@szEtypeid,@szKtypeId,-1*@v253_total,@period,'',@deptid,@branchid,6
		)  
		
		INSERT  INTO dlya --转入客户 应付增加
		(
		vchcode,[Date],vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@AP_ID,@szBtypeid,@szEtypeid,@szKtypeId,1*@v253_total,@period,'',@deptid,@branchid,6
		) 
	END
	ELSE IF @PHID=12 --应收冲应付
	BEGIN
		INSERT  INTO dlya --转出客户 应付减少
		(
		vchcode,[Date],vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@AR_ID,@szBtypeid2,@szEtypeid,@szKtypeId,-1*@v253_total,@period,'',@deptid,@branchid,6
		)  
		
		INSERT  INTO dlya --转入客户 应付减少
		(
		vchcode,[Date],vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,Dtypeid,branchid,billtype
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,@AP_ID,@szBtypeid,@szEtypeid,@szKtypeId,-1*@v253_total,@period,'',@deptid,@branchid,6
		) 
	END
	
	EXEC @nret=modifydbfNEW   'dlya',@nVchType,'',@nVchcode,'',@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error
    goto finish  
END	

IF @nVchType IN ( 115, 116, 128, 129, 130, 131 ) 
BEGIN ------应收款减少、增加单   
	SELECT @dTempTotal=SUM(total) FROM bakdly where vchcode =@nVchcode AND Usedtype=1 AND Total<>0 
	--应收款变化  
	IF @nVchtype IN ( 115, 129, 130 ) 
		SELECT  @dTempTotal = -1 * @dTemptotal  


	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,Comment,total,period,usedtype,Dtypeid,branchid,BillType
	)
	SELECT 
	@nVchcode,@tDate,@nVchType,Atypeid,@szBtypeid,@szEtypeid,@szKtypeId,Comment,Total,@period,Usedtype,@deptid,@branchid,6
	FROM bakdly where vchcode =@nVchcode AND Usedtype=1 AND Total<>0 
	ORDER BY DlyOrder
	
	IF @nVchtype NOT IN ( 130, 131 ) 
	BEGIN  
		IF @procType = 'FZCS'
			EXEC FZUpdateYSYFTotal @dTempTotal, @szBtypeid, @nVchcode,@branchid,@nvchtype   		
		INSERT  INTO dlya
		(
		vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,total,period,usedtype,branchid,Dtypeid,billtype
		)
		VALUES  (
		@nVchcode,@tDate,@nVchType,CASE WHEN @nvchtype IN ( 115, 116 ) THEN @AR_ID   ELSE @AP_ID END,
		@szBtypeid,@szEtypeid,@szKtypeId,@dTempTotal,@period,'',@branchid,@deptid,6
		)  
	END  
	-- 因total为正，所以此处再反号  
	IF @nVchtype IN ( 115, 129, 130 ) 
		UPDATE  dlyndx 	SET     Total = -( @dTempTotal ),BillType = 6	WHERE   vchcode = @nVchcode  
	ELSE 
		UPDATE  dlyndx	SET     Total = ( @dTempTotal ),	BillType = 6	WHERE   vchcode = @nVchcode  
	EXEC @nret=modifydbfNEW   'dlya',@nVchType,'',@nVchcode,'',@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error
    goto finish  
END

IF @nVchType = 125 ---------会计凭证单 
BEGIN
	INSERT  INTO dlya
	(
	vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,Comment,total,period,usedtype,branchid,Dtypeid,BillType)
	SELECT
	@nVchcode,@tDate,@nVchType,Atypeid,Btypeid,@szEtypeid,@szKtypeId,Comment,Total,@period,Usedtype,@branchid,@deptid,6
	FROM BakDly WHERE Vchcode =@nVchcode
	ORDER BY DlyOrder
	UPDATE  dlyndx  SET total = ABS(@dTempTotal),billtype = 6 WHERE   vchcode = @nVchcode  
	EXEC @nret=modifydbfNEW   'dlya',@nVchType,'',@nVchcode,'',@szptypeid OUTPUT,-1,@OldVchcode
	IF @nret<0
		GOTO error
    goto finish  
END

--以下处理VIP
VIP:
IF @nVchType IN ( 11, 45,24,12, 100 )  
BEGIN   

	 --------------------新增加Vip卡消费金额处理－－－－－－－－－－－－－－BEGIN  
    IF @nVchType IN ( 12, 100 )  AND @account <> 'COMMONPOSLSJC'--零售单,专柜零售独处理VIP BEGIN ，要非POS结存草稿才走此过  
    BEGIN  
        SELECT  @execsql = 'declare Vip_crusor cursor for '
                + 'Select atypeid,BranchID,VipCardID,Ktypeid,SUM(Tax_Total) as Tax_Total,SUM(SaleMoney) as SaleMoney,Sum(total) as Total,'
                + 'sum(case when saleMode = 1 then 0 else  SaleMoney end) as xfje  '
                + '   FROM BakDly ' + '   Where Vchcode= '
                + CAST(@nVchcode AS VARCHAR(10))
                + '   and vipcardid<>0 GROUP BY BranchID ,VipCardID,Ktypeid,atypeid'  
        EXEC ( @execsql
            )  
        OPEN Vip_crusor  
        FETCH NEXT FROM Vip_crusor INTO @szatypeid, @BranchID, @VipCardID, @szktypeid, @dTax_total,@SaleMoney, @dTotal,@xfje  
        WHILE @@FETCH_STATUS = 0   
        BEGIN  
			set @dTax_total=ROUND(@dTax_total,@dig_total)
			set @SaleMoney=ROUND(@SaleMoney,@dig_total)
			set @dTotal=ROUND(@dTotal,@dig_total)
			set @xfje=ROUND(@xfje,@dig_total)
			
            SET @VipConsumeTotal = 0  
          --  SET @xfje = 0     
            SET @vipsalemoneyTemp = 0  

            IF @szAtypeid = '0000299999'      --如果是储值卡要扣除卡上存储金额  
            BEGIN  
                SET @VipConsumeTotal = -1 * @dTotal  
                IF @vipCardid <> 0 
                BEGIN  
                    EXEC @nRet= FZUpdateVipcardTotal @nVchcode,@vipcardid, @VipConsumeTotal,@szKtypeid, @InputNO,@MenDataBase, @szatypeido,@szATypeID, @oldvchcode,@tDate, @BranchID  
                    IF @nRet <> 0 
                        GOTO error    
                END  
            END  
            ELSE   --算积分  
            BEGIN  
                IF @vipCardid = @LSvipCardid --此前余额  
                BEGIN  
					SELECT  @VipiniTotal = savemoney  FROM    vipcards WHERE   cardid = @vipCardid  
                    UPDATE  dlyndx SET     ForevipBalance = ISNULL(@VipiniTotal, 0) WHERE   vchcode = @nVchcode  
                END  
                --SET @SaleMoney = @dTax_total  
--                 IF @SaleMode <> '1' 
--                 BEGIN  
--                    SET @xfje = @SaleMoney  
-- -- 	     				--if @nvchtype not in(100) --代销（商场）零售单,现在以机构来区分零售单  
-- --                     IF not EXISTS ( SELECT TOP 1  1 FROM    branch WHERE   branchtype = 3 AND branchid = @BranchID ) 
-- --                         SET @xfje = @dTax_total  
-- --                     ELSE 
-- --                         SET @xfje = @SaleMoney  
--                 END  
                SET @vipsalemoneyTemp = @Salemoney  
                SELECT  @xfje = ( @xfje )  
        

                IF EXISTS ( SELECT  1 FROM    VIPCardExpand ve,Vipcards v WHERE   ve.ExpandType = 2 AND ve.CardID = v.CardTypeID  AND v.cardid = @vipCardid ) 
                BEGIN   
						--零售单有多张VIP，所以此前积分只处理最后一张录入的VIP                              
                    IF @vipCardid = @LSvipCardid  --and @SaleMode <> '1' 
                        UPDATE  dlyndx  SET     LastUnDoIntegral = ( SELECT undoIntegral  FROM   vipcards WHERE  cardid = @vipCardid) WHERE   vchcode = @nVchcode   

                    EXEC @retvip= FZWriteIntegralDetail @vipCardid,@szKtypeid, @tDate, @nVchcode,@vipsalemoneyTemp, @xfje,@szGeneralTotal OUTPUT  

                    SET @RetTotalSaleMoney = @vipsalemoneyTemp  
                    SET @RetTotalJFJE = @xfje  
                    IF @retVip <> 0 
                        BEGIN  
                            SET @nRet = -400  
                            GOTO error  
                        END  
						--零售单有多张VIP，所以此前积分只处理最后一张录入的VIP                              
                    IF @vipCardid = @LSvipCardid --and @SaleMode <> '1'  
                        UPDATE  dlyndx  SET     CurrUnDoIntegral = ( SELECT undoIntegral FROM   vipcards WHERE  cardid = @vipCardid)  WHERE   vchcode = @nVchcode  
							-- 改成未处理积分(因为BS加了积分转储值后，AllIntegral, CurrUnDoIntegral这两者之间可能不等)    

							--update dlyndx Set CurrUnDoIntegral=(Select AllIntegral from vipcards where cardid=@vipCardid) where vchcode=@nVchcode      
                END  
            END  
            FETCH NEXT FROM Vip_crusor INTO @szatypeid, @BranchID, @VipCardID, @szktypeid,@dTax_total, @SaleMoney, @dTotal ,@xfje
        END  
        CLOSE Vip_crusor  
        DEALLOCATE Vip_crusor  
        IF @nVchType IN ( 12, 100, 226 )  AND EXISTS ( SELECT 1 FROM   POSRetailbill WHERE  draftbillcode = @oldVchcode ) and @TempExpandid = 'LSJC'  
        BEGIN  
            UPDATE  POSRetailbill  SET     draftBillcode = @nVchcode WHERE   draftbillcode = @oldVchcode   
            IF ( @@rowcount < 0  OR @@error <> 0 ) 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END     
        END  

		-- 如果是pos零售结存来的单据要改原始pos零售单据对应的结存单据的编号 (此处代码目前不可能执行到)
        IF @nVchType IN ( 12, 100, 226 )  AND EXISTS ( SELECT 1 FROM   dbo.tpx_SaleIndex WHERE  DraftVchcode = @oldVchcode )  and @account = 'COMMONPOSLSJC'
        BEGIN  
            UPDATE  tpx_SaleIndex  SET     DraftVchcode = @nVchcode WHERE   DraftVchcode = @oldVchcode  AND @oldVchcode<>0
            IF ( @@rowcount < 0  OR @@error <> 0 ) 
            BEGIN  
                SET @nRet = -2  
                GOTO error  
            END  
        END  
    END --零售单,专柜零售独处理VIP END  
    ELSE 
    BEGIN  

        SET @vipCardid = @LSvipCardid -- 等于表头VIP,算积分  
        IF @vipCardid <> 0 
        BEGIN  
            IF @account = 'COMMONPOSLSJC'  --BackMoney字段存储的是积分金额，根据此值配合卡类型中的累积积分设置，  
                SET @xfje = @backMoney  
            IF ( @szatypeido <> 'TRANSFER' )  AND EXISTS ( SELECT 1  FROM   VIPCardExpand ve, Vipcards v WHERE  ve.ExpandType = 2 AND ve.CardID = v.CardTypeID AND v.cardid = @vipCardid ) 
            BEGIN                               
                UPDATE  dlyndx  SET     LastUnDoIntegral = ( SELECT undoIntegral FROM   vipcards WHERE  cardid = @vipCardid) WHERE   vchcode = @nVchcode  
                EXEC @retvip= FZWriteIntegralDetail @vipCardid,@szKtypeid, @tDate, @nVchcode,@vipsalemoneyTemp, @xfje,@szGeneralTotal OUTPUT,@OldVchcode

                SET @RetTotalSaleMoney = @vipsalemoneyTemp  
                SET @RetTotalJFJE = @xfje  
                IF @retVip <> 0 
                BEGIN  
                    SET @nRet = -400  
                    GOTO error  
                END  
		 --update dlyndx Set CurrUnDoIntegral=(Select AllIntegral from vipcards where cardid=@vipCardid) where vchcode=@nVchcode    
		 -- 改成未处理积分(因为BS加了积分转储值后，AllIntegral, CurrUnDoIntegral这两者之间可能不等)    
                UPDATE  dlyndx  SET     CurrUnDoIntegral = ( SELECT undoIntegral FROM   vipcards WHERE  cardid = @vipCardid) WHERE   vchcode = @nVchcode   
            END  


            IF @account = 'COMMONPOSLSJC' --POS结存草稿不扣减VIP储值，因为POS端已经扣除了  
            BEGIN  
				---------modify by 老罗2012-11-26 此处新pos端已经把vip的储值金额扣减了，vip的此前余额不能用过账时的vip储值金额来反写
                --SELECT  @VipiniTotal = savemoney  FROM    vipcards WHERE   cardid = @vipCardid  
                --UPDATE  dlyndx  SET     ForevipBalance = ISNULL(@VipiniTotal, 0) WHERE   vchcode = @nVchcode  
				--处理主单上对应的vip的此前余额问题
                IF EXISTS ( SELECT  1
                            FROM    dbo.tpx_SaleVipList a
                                    INNER JOIN dbo.tpx_SaleIndex b ON a.ZBKeyId = b.keyId
                            WHERE   b.DraftVchcode = @oldVchcode ) 
                BEGIN
                    DECLARE @OLdVipTotal NUMERIC(24, 10) ,
                        @NewVipTotal NUMERIC(24, 10)
                    SET @OLdVipTotal=0
                    SET @NewVipTotal=0
                    SELECT  @OLdVipTotal = a.Total ,
                            @NewVipTotal = c.SaveMoney
                    FROM    dbo.tpx_SaleVipList a
                            INNER JOIN dbo.tpx_SaleIndex b ON a.ZBKeyId = b.keyId
                            INNER JOIN dbo.VipCards c ON b.VipCardID = c.CardID
                    WHERE   b.DraftVchcode = @oldVchcode AND a.VipID=@vipCardid
              
                    UPDATE  dlyndx
                    SET     ForeVIPBalance = CAST(ISNULL(@NewVipTotal, 0)
                            + CASE WHEN SIGN(Total) >=0
                                   THEN ISNULL(@OLdVipTotal, 0)
                                   ELSE -1 * ISNULL(@OLdVipTotal, 0)
                              END AS NUMERIC(24, 10))
                    WHERE   Vchcode = @nVchcode
			
                END
				
    
    
                IF @@ROWCOUNT < 0 OR @@ERROR <> 0 
                BEGIN  
                    IF @procType = 'FZCS' AND @CallSelf = 0 
                        ROLLBACK TRAN Account  
                    RETURN -2  
                END  
				 --之前已经写入 cardfilllist，而后 VchCode改变，所以 PosVchCode也要改变  
                UPDATE  cardfilllist SET   VchCode=@nVchcode 
                FROM cardfilllist a INNER JOIN  dbo.tpx_SaleIndex b 
                 ON a.PosVchCode=b.PosVchCode
                WHERE b.DraftVchcode=@oldVchcode
                
            END  
        END  
        IF @nVchType in (11,24,45) --销售出库单、销售换货、销售退货 处理VIP储值支付(要放在积分之后）  6.1改成了多卡支付，所以要循环
        BEGIN  
            SELECT  @VipiniTotal = savemoney FROM    vipcards  WHERE   cardid = @vipCardid  
            UPDATE  dlyndx SET     ForevipBalance = ISNULL(@VipiniTotal, 0) WHERE   vchcode = @nVchcode  
            SELECT  @execsql = 'declare Vip_crusor cursor for '
                    + 'Select atypeid,BranchID,saleMode ,VipCardID,Ktypeid,SUM(Tax_Total) as Tax_Total,SUM(SaleMoney) as SaleMoney,Sum(total) as Total'
                    + '   FROM BakDly ' + '   Where Vchcode= '
                    + CAST(@nVchcode AS VARCHAR(10))
                    + '   and vipcardid<>0 and atypeid=''0000299999'' GROUP BY BranchID,saleMode ,VipCardID,Ktypeid,atypeid'  
            EXEC ( @execsql
                )  
            OPEN Vip_crusor  
            FETCH NEXT FROM Vip_crusor INTO @szatypeid,@BranchID, @SaleMode, @VipCardID, @szktypeid,@dTax_total, @SaleMoney, @dTotal  
            WHILE @@FETCH_STATUS = 0   
            BEGIN  
				set @dTax_total=ROUND(@dTax_total,@dig_total)
				set @SaleMoney=ROUND(@SaleMoney,@dig_total)
				set @dTotal=ROUND(@dTotal,@dig_total)
				
                SET @VipConsumeTotal = 0  
                SET @xfje = 0     
                SET @vipsalemoneyTemp = 0  
				IF @nVchType in (11,24)
	                SET @VipConsumeTotal = -1 * @dTotal  
				ELSE 
					SET @VipConsumeTotal =  @dTotal  
                IF @vipCardid <> 0 
				BEGIN  
					EXEC @nRet= FZUpdateVipcardTotal @nVchcode,@vipcardid, @VipConsumeTotal,@szKtypeid, @InputNO,@MenDataBase, @szatypeido,@szATypeID, @oldvchcode,@tDate, @BranchID  
					IF @nRet <> 0 
					GOTO error    
				END  
                FETCH NEXT FROM Vip_crusor INTO @szatypeid,@BranchID, @SaleMode, @VipCardID,@szktypeid, @dTax_total, @SaleMoney,@dTotal  
            END  
            CLOSE Vip_crusor  
            DEALLOCATE Vip_crusor  
        END  
    END  
	GOTO FINISH
END  

IF @nVchType = 125 ---------会计凭证单  
BEGIN  
    UPDATE  dlyndx SET     total = ABS(@dTempTotal), billtype = 6 WHERE   vchcode = @nVchcode  
END    
GOTO finish  
--在处理加盟店配送销售时，在删除配送单草稿以前，先生成一张配送验收单草稿（更该dlyndx表中相应单据的标志为4：配送单草稿）  
--再删除配送草稿，等待验收过帐以后  
--再删除验收草稿。  
------------------------------会计凭证处理结束--------------------------  
-----对科目类型进行过帐  
  
    finish:  

    DECLARE @draft INT  
    SELECT  @draft = draft
    FROM    dlyndx
    WHERE   vchcode = @nvchcode  

	 --判断主单是否存在  
    IF NOT EXISTS ( SELECT  Vchcode FROM    dlyndx WHERE   vchcode = @nVchcode ) 
    BEGIN  
        SET @nRet = -888  
        GOTO error  
    END  
	----------------------------  
     --删除对应草稿表中相应明细  
     --过帐成功后将，dlyndx表中的相应记录的draft标志位修改为2（将‘3’改为2）  

    IF @draft <> 4 
    BEGIN  
        IF @draft IN ( 10, 9 ) AND NOT EXISTS ( SELECT 1  FROM   dlyndx  WHERE  vchcode = @oldvchcode ) 
        BEGIN  
            SET @nRet = -206  
            GOTO error  
        END  
        UPDATE  dlyndx  SET     draft = 2,Period = @Period,AccountTime = GETDATE() WHERE   vchcode = @nVchcode  AND draft <> 4  
        IF ( @@rowcount < 0 OR @@error <> 0) 
        BEGIN  
            SET @nRet = -200  
            GOTO error  
        END  
		
	  --过账成功后判断是否删除原始单据 @deldraft=0 不删除，@deldraft=1 要删除  
	  --(@draft=6表示通过上下传来的单据,@draft=10表示零售结存来的单据  
	  -- 以上两种单据只要成功过账就一定要删除原始单据)  
        IF @DelDraft = 1 OR @draft IN ( 6, 10, 9 )  
        BEGIN  
            IF EXISTS ( SELECT  1  FROM    dlyndx WHERE   vchcode = @OldVchcode ) 
            BEGIN  
				 	--处理虚拟库存中草稿数  (前移) 又移回来了 2012-05-21
					DECLARE @retVirtual INT  
					EXEC @retVirtual= FZModifyVirtualGoods 'BakDly','', @OldVchcode, 0,'',0  
		        	IF @retVirtual < 0 
		            BEGIN  
		                SET @nRet = @retVirtual  
		                GOTO error  
		            END 
				
                    IF EXISTS ( SELECT  1 FROM    bakdlydetail  WHERE   Vchcode IN (SELECT  Vchcode FROM dlyndx dn  WHERE   dn.vchcode = @OldVchcode AND dn.draft <> 2 ) ) 
                    BEGIN  
                        DELETE  FROM bakdlydetail 
                        WHERE    Vchcode IN (SELECT  Vchcode FROM dlyndx dn  WHERE   dn.vchcode = @OldVchcode AND dn.draft <> 2 ) 
                        IF ( @@rowcount < 0  OR @@error <> 0) 
                        BEGIN  
                            SET @nRet = -200  
                            GOTO error  
                        END  
                        IF EXISTS ( SELECT  1  FROM    dlyndx dn WHERE   dn.vchcode = @OldVchcode AND dn.draft <> 2 ) 
                        BEGIN    
                            DELETE  FROM bakdly  WHERE   vchcode = @OldVchcode  
                            IF ( @@rowcount < 0 OR @@error <> 0) 
                            BEGIN  
                                SET @nRet = -200  
                                GOTO error  
                            END  
                        END  
                    END  
                    ELSE 
                    BEGIN  
                        IF EXISTS ( SELECT  1  FROM    dlyndx dn WHERE   dn.vchcode = @OldVchcode AND dn.draft <> 2 ) 
                        BEGIN  
                            DELETE  FROM bakdly WHERE   vchcode = @OldVchcode  
                            IF ( @@rowcount < 0OR @@error <> 0) 
                            BEGIN  
                                SET @nRet = -200  
                                GOTO error  
                            END  
                        END  
                    END  

                    DELETE  FROM dlyndx WHERE   vchcode = @OldVchcode  AND draft <> 2  
					
                    IF (  @@rowcount< 0 OR @@error <> 0)  
                    BEGIN  
                        SET @nRet = -200  
                        GOTO error  
                    END  
            END  
        END  
    END  
    --删除对应草稿表中相应明细（新生成单据）  
    IF  @draft NOT IN ( 1, 4, 8 )  
    BEGIN  
        IF @draft = 9 
        BEGIN  
            EXEC @retVirtual= FZModifyVirtualGoods 'BakDly', '',@OldVchcode, 0,'',0  
            IF @retVirtual < 0 
            BEGIN  
                SET @nRet = @retVirtual
                GOTO error  
            END  
        END  

		IF EXISTS ( SELECT  1 FROM    bakdlydetail WHERE   vchcode = @nVchcode ) 
		BEGIN  
			DELETE  FROM bakdlydetail WHERE    vchcode = @nVchcode 
			IF ( @@rowcount < 0 OR @@error <> 0) 
			BEGIN  
				SET @nRet = -200  
				GOTO error  
			END  
			DELETE  FROM bakdly WHERE   vchcode = @nVchcode  
			IF ( @@rowcount < 0 OR @@error <> 0) 
			BEGIN  
				SET @nRet = -200  
				GOTO error  
			END  
		END  
		ELSE 
		BEGIN  
			DELETE  FROM bakdly WHERE   vchcode = @nVchcode  
			IF ( @@rowcount < 0 OR @@error <> 0) 
			BEGIN  
				SET @nRet = -200  
				GOTO error  
			END  
		END  
        IF EXISTS(SELECT 1 FROM dbo.DZTVchcode WHERE vchcode=@OldVchcode)
        BEGIN
			UPDATE dbo.DZTVchcode SET vchcode=@nVchcode WHERE vchcode=@OldVchcode
			IF ( @@rowcount < 0 OR @@error <> 0) 
			BEGIN  
				SET @nRet = -2  
				GOTO error  
			END  
        END 
    END  
    SELECT  @szTemp = subvalue FROM    sysdata WHERE   subname = 'Enddate'  
    IF @tdate > @szTemp 
	BEGIN  
		UPDATE  sysdata SET     subvalue = @tdate WHERE   subname = 'Enddate'  
		IF ( @@rowcount < 0 OR @@error <> 0) 
		BEGIN  
			SET @nRet = -200  
			GOTO error  
		END  
	END  
    UPDATE  dlyndx    SET     flag = 1    WHERE   vchcode = @nVchcode  
    IF ( @@rowcount < 0  OR @@error <> 0) 
    BEGIN  
        SET @nRet = -139  
        GOTO error  
    END  
  
    IF @nVchtype = 232 OR @nVchtype = 224 --单据验收后，改变原来单据的状态为已验收  
    BEGIN  
        UPDATE  DlyNdx SET     CheckAndAccept = 1 WHERE   VchCode IN ( SELECT TOP 1  dlyvchcode  FROM   dlyndx  WHERE  vchcode = @nVchcode )  
    END  
    GOTO Successed  

    Successed:
		
		if exists(select 1 from sysdata where subname='ProcTypeName' and subvalue='FZBS')
		begin
			--处理dlyndxB
			if @DelDraft=1
				delete from dlyndxb where vchcode=@oldvchcode
			
			IF @nVchType in(12,100,17,218) AND @account = 'COMMONPOSLSJC' and not exists(select 1 from dlyndxb where vchcode=@nVchcode)
			begin
				insert into DlyNdxB(vchcode,metypeid,petypeid,mdate,pdate)
				values(@nVchcode,'',@operatorid,getdate(),getdate())
			end
			ELSE
				UPDATE DlyNdxB SET vchcode=@nVchcode,petypeid=@operatorid,pdate=GETDATE() WHERE vchcode = @nVchcode
		end
		
	    IF @account = 'COMMONPOSLSJC' AND @OldVchcode <> 0 --POS结存关联 CommonPosSaleIndex.DraftVchcode 号因为草稿过账删除了，要重新更新  
	    BEGIN  
	        UPDATE  dbo.tpx_SaleIndex
	        SET     DraftVchcode = @nVchcode,
					draft=2
	        WHERE   DraftVchcode = @OldVchcode  
	    END  
	   
		 --将审核流程复制到新单据(同价配货、变价配货除外,因为过账虽是用新单，但过账后是删除新单的),这个要放在验收过账之前  
	    IF (NOT ( @nVchtype IN ( 212, 218 ) AND @draft1 = 7))  AND EXISTS ( SELECT TOP 1  1 FROM   AuditingBill WHERE  Vchcode = @OldVchcode ) 
	    BEGIN  
	        if @nVchtype IN (7,8,211,221,223 )
	            UPDATE  AuditingBill
	            SET     VchCode = @nVchcode
	            WHERE   Vchcode = @OldVchcode and  billindextype = 0
	        else
	            UPDATE  AuditingBill
	            SET     VchCode = @nVchcode
	            WHERE   Vchcode = @OldVchcode and  billindextype = 1
	    END  
	
	    DECLARE @tempret INT  
	    SET @tempret = 0  
		
		--要启用验收,且验收方有经手人，则验收方经手人清空  
	    IF @nVchtype IN ( 222, 234 ) AND @CheckAndAccept = 1 AND @nVchcodenew <> 0  AND @TempEtypeID<>''
			  UPDATE dlyndx set etypeid='' where vchcode =@nVchcodenew  

		IF @nVchtype IN ( 222, 234 ) AND @CheckAndAccept = 0 AND @nVchcodenew <> 0  --不启用验收,且验收方有经手人，则验收方直接过账  
		BEGIN  
			IF @TempEtypeID = '' 
			BEGIN  
				SET @tempret = 1 --返回值大于0，表明单据待验收  
			END  
			ELSE 
			BEGIN  
				SET @szktypeido = '' --传的老单号，置空  
				SET @szbtypeido = 'check'   
				EXEC @nRet = FZZ_CreateDly @nVchcodenew,@szptypeido OUTPUT, @szbtypeido OUTPUT,@szatypeido OUTPUT, 
				@szktypeido OUTPUT,@szGeneralTotal OUTPUT, @RetTotalSaleMoney OUTPUT,@RetTotalJFJE OUTPUT, 0, @operatorid, 1  
				                 -- return @nRet  
				SET @tempret = @nRet  
			END  
		END  
		IF @tempret < 0 
		BEGIN  
		    IF @procType = 'FZCS'  AND @CallSelf = 0 
		    BEGIN
		        ROLLBACK TRAN Account 
		    END
		END  
		ELSE 
		BEGIN  
		    IF @procType = 'FZCS' AND @CallSelf = 0 
		        COMMIT TRAN Account 
		END  
		IF @tempret <> 0 
			RETURN @tempret  
		ELSE 
			RETURN 0   

	error:  
		IF EXISTS ( SELECT  d.cursor_name FROM    master.dbo.syscursors d,master.dbo.syscursortables dt 
		WHERE   d.cursor_handle = dt.cursor_handle AND dt.dbname = DB_NAME()   AND cursor_name = 'Vip_crusor' )   --增加释放2011年8月8日16:15:40黄文武
		BEGIN  
			CLOSE Vip_crusor  
			DEALLOCATE Vip_crusor  
		END 
		IF @procType = 'FZCS' AND @CallSelf = 0 
		    ROLLBACK TRAN Account  
		
		SELECT  @szptypeido = @szptypeid  
		SELECT  @szbtypeido = @szbtypeid  
		SELECT  @szatypeido = @szatypeid  
		SELECT  @szktypeido = @szktypeid  
	  
	    IF EXISTS ( SELECT  1 FROM    transbill WHERE   vchcode = @nVchcode ) 
	    BEGIN  
	        DELETE  FROM TransBilldetail
	        WHERE   EXISTS ( SELECT dlyorder FROM   TransBill  WHERE  vchcode = @nVchcode )  
	        DELETE  FROM TransBill WHERE   vchcode = @nVchcode  
	    END  
	 --清除垃圾草稿(过账失败删除新生成单据)  
	    IF EXISTS ( SELECT  1 FROM    dlyndx WHERE   draft IN ( 3, 7, 10, 6, 9 )  AND vchcode = @nVchcode ) 
	    BEGIN  
	        DELETE  FROM bakdlydetail  WHERE   dlyorder IN ( SELECT    dlyorder  FROM      bakdly  WHERE     vchcode = @nVchcode )  
	        DELETE  FROM bakdly  WHERE   vchcode = @nVchcode   
	        DELETE  FROM dlyndx  WHERE   vchcode = @nVchcode  
					
			--处理dlyndxB
			DELETE FROM DlyNdxB WHERE vchcode=@nVchcode
	    END  
	    RETURN @nRet  
	    SET nocount OFF  
  

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/******************************************20130703********************************************/
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZGetFinanceData]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZGetFinanceData]
GO


CREATE PROCEDURE FZGetFinanceData
    (
      @ctypeid VARCHAR(1500),
      @begindate VARCHAR(10) ,
      @EndDate VARCHAR(10) ,
      @unite BIT --1:要合并当天的单据 0：不合并
    )
AS 
    IF @begindate > @Enddate 
        BEGIN
            SELECT  'A'
            RETURN -1 --设置日期不正确
        END

     --资产合计  【支出类】为正为借方 为负为贷方		 --【负债合计】【收入类】为正为贷方 为负为借方		



    IF @unite = 1 
        BEGIN
            SELECT  number ,
                    date ,
                    bname1 ,
                    bname2 ,
                    ename ,
                    dmname ,
                    SUM(c.Total) Total ,
                    SUM(c.Total2) Total2 ,
                    ufusercode ,
                    summary ,
                    type,usercode
            FROM    ( SELECT    number ,
                                date ,
                                bname1 ,
                                bname2 ,
                                ename ,
                                dmname ,
                                CASE a.Total
                                  WHEN 0 THEN 2
                                  ELSE 1
                                END AS type ,
                                a.Total ,
                                ( a.Total2 ) Total2 ,
                                ufusercode ,
                                summary,usercode
                      FROM      ( SELECT    dn.number ,
                                            da.[date] ,
                                            ( SELECT    fullname
                                              FROM      btype b
                                              WHERE     b.typeid = da.btypeid
                                                        AND LEFT(da.btypeid, 5) IN (
                                                        '00001', '00007' )
                                            ) bName1 ,
                                            ( SELECT    fullname
                                              FROM      btype b
                                              WHERE     b.typeid = da.btypeid
                                                        AND LEFT(da.btypeid, 5) IN (
                                                        '00002', '00004',
                                                        '00003','00006' )
                                            ) bName2 ,
                                            ( SELECT    fullname
                                              FROM      employee e
                                              WHERE     E.typeid = da.etypeid
                                            ) EName ,
                                            ( SELECT    fullname
                                              FROM      department dm
                                              WHERE     dm.typeid = dn.Dtypeid
                                            ) DMName ,
                                            CASE WHEN LEFT(da.atypeid, 5) IN (
                                                      '00001', '00004',
                                                      '00007' )
                                                      AND da.total > 0
                                                 THEN ABS(da.Total)
                                                 WHEN LEFT(da.atypeid, 5) IN (
                                                      '00002', '00003' )
                                                      AND da.total < 0
                                                 THEN ABS(da.Total)
                                                 ELSE 0
                                            END AS Total ,
                                            CASE WHEN LEFT(da.atypeid, 5) IN (
                                                      '00001', '00004',
                                                      '00007' )
                                                      AND da.total < 0
                                                 THEN ABS(da.Total)
                                                 WHEN LEFT(da.atypeid, 5) IN (
                                                      '00002', '00003' )
                                                      AND da.total > 0
                                                 THEN ABS(da.Total)
                                                 ELSE 0
                                            END AS Total2 ,
                                            da.ufusercode ,
                                            summary,da.usercode
                                  FROM      dlyndx dn ,
                                            ( SELECT    da.* ,
                                                        a.rec AS ufusercode,a.usercode
                                              FROM      dlya da ,
                                                        atype a
                                              WHERE     da.branchid = a.branchid
                                                        AND da.atypeid = a.typeid
							and da.total <> 0
                                            ) da
                                  WHERE     dn.redold = 'F'
											AND EXISTS(
											SELECT 1 FROM dbo.fn_split(@ctypeid,',') t WHERE dn.branchid LIKE t.a+'%' AND dn.vchtype not in(212, 218, 222, 234)
											UNION ALL SELECT 1 FROM dbo.fn_split(@ctypeid,',') t WHERE dn.branchid2 LIKE t.a+'%' AND dn.vchtype in(212, 218, 222, 234)								
											) 
                                           -- AND dn.VchType NOT IN ( 232, 234 )
                                            AND dn.vchcode = da.vchcode
                                            AND dn.date BETWEEN @Begindate AND @EndDate
                                ) a
                    ) AS c
            GROUP BY number ,
                    [date] ,
                    bname1 ,
                    bname2 ,
                    ename ,
                    dmname ,
                    ufusercode ,
                    summary ,
                    type,usercode
		ORDER BY number                    
            IF @@rowcount = 0  --没有记录
                BEGIN	
                    SELECT  'A'
                    RETURN -2
                END
            ELSE 
                RETURN 0
        END
    ELSE 
        BEGIN
            SELECT  dn.number ,
                    da.[date] ,
                    ( SELECT    fullname
                      FROM      btype b
                      WHERE     b.typeid = da.btypeid
                                AND LEFT(da.btypeid, 5) IN ( '00001', '00007' )
                    ) bName1 ,
                    ( SELECT    fullname
                      FROM      btype b
                      WHERE     b.typeid = da.btypeid
                                AND LEFT(da.btypeid, 5) IN ( '00002', '00004',
                                                             '00003','00006' )
                    ) bName2 ,
                    ( SELECT    fullname
                      FROM      employee e
                      WHERE     E.typeid = da.etypeid
                    ) EName ,
                    ( SELECT    fullname
                      FROM      department dm
                      WHERE     dm.typeid = dn.Dtypeid
                    ) DMName ,
                    CASE WHEN LEFT(da.atypeid, 5) IN ( '00001', '00004',
                                                       '00007' )
                              AND da.total > 0 THEN ABS(da.Total)
                         WHEN LEFT(da.atypeid, 5) IN ( '00002', '00003' )
                              AND da.total < 0 THEN ABS(da.Total)
                         ELSE 0
                    END AS Total ,
                    CASE WHEN LEFT(da.atypeid, 5) IN ( '00001', '00004',
                                                       '00007' )
                              AND da.total < 0 THEN ABS(da.Total)
                         WHEN LEFT(da.atypeid, 5) IN ( '00002', '00003' )
                              AND da.total > 0 THEN ABS(da.Total)
                         ELSE 0
                    END AS Total2 ,
                    da.ufusercode ,
                    summary,da.usercode
            FROM    dlyndx dn ,
                    ( SELECT    da.* ,
                                a.rec AS ufusercode,
				a.usercode
                      FROM      dlya da ,
                                atype a
                      WHERE     da.branchid = a.branchid
                                AND da.atypeid = a.typeid
				and da.total <> 0
                    ) da
            WHERE   dn.redold = 'F'
					AND EXISTS(
					SELECT 1 FROM dbo.fn_split(@ctypeid,',') t WHERE dn.branchid LIKE t.a+'%' AND dn.vchtype not in(212, 218, 222, 234)
					UNION ALL SELECT 1 FROM dbo.fn_split(@ctypeid,',') t WHERE dn.branchid2 LIKE t.a+'%' AND dn.vchtype in(212, 218, 222, 234)		) 
                   -- AND dn.VchType NOT IN ( 232, 234 )
                    AND dn.vchcode = da.vchcode
                    AND dn.date BETWEEN @Begindate AND @EndDate
		   ORDER BY number  
            IF @@rowcount = 0  --没有记录
                BEGIN	
                    SELECT  'A'
                    RETURN -2
                END
            ELSE 
                RETURN 0
        END
	


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/******************************************20130705********************************************/
--增加IC卡支持

IF NOT EXISTS(SELECT 1 FROM sysdata WHERE subname='IsVipICCard')
BEGIN
	INSERT INTO sysdata(subname,subvalue,subcomment)
	VALUES('IsVipICCard','0','是否启用IC卡设备')
END
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE subname='VipICMachine')
BEGIN
	INSERT INTO sysdata(subname,subvalue,subcomment)
	VALUES('VipICMachine','','IC卡设备名称')
END
IF NOT EXISTS(SELECT 1 FROM sysdata WHERE subname='ICCardMark')
BEGIN
	INSERT INTO sysdata(subname,subvalue,subcomment)
	VALUES('ICCardMark','','IC卡设备会员卡标识')
END
GO


SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GoodsRetailTotal]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GoodsRetailTotal]
GO

SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO
/*      
商品零售综合分析
*/      
Create PROC GoodsRetailTotal
(      
  @dynTable as DynParameterTable readonly
  , @sqlCmd nvarchar(max) out --输出参数, 业务Sql片段
  , @decSql nvarchar(max) out --输出参数，参数声明Sql片段
  , @specSql nvarchar(max) out --输出参数，参数赋值Sql片段    
)       
AS 
BEGIN
SET NOCOUNT ON

DECLARE @SQLCmd1 VARCHAR(MAX)

SET @SQLCmd1 = N''
set @decSql = N'@dynParamTable as DynParameterTable readonly'
set @specSql = N'@dynParamTable'

SELECT @decSql += nchar(10) + nchar(9) + N', @' + ParaField + N' ' + DataType,
	   @specSql += nchar(10) + nchar(9) + isnull(N', ''' + ParaValue + N'''', ', null')
from @dynTable
WHERE datatype <> ''

DECLARE @branchidEx NVARCHAR(60)				SELECT @branchidEx = ISNULL(ParaValue,'') FROM @dynTable WHERE ParaField = 'branchid'
DECLARE @ktypeidEx NVARCHAR(60)					SELECT @ktypeidEx = ISNULL(ParaValue,'') FROM @dynTable WHERE ParaField = 'ktypeid'
DECLARE @billdate_sEx datetime					SELECT @billdate_sEx = ISNULL(ParaValue,'') FROM @dynTable WHERE ParaField = 'billdate_s'
DECLARE @billdate_eEx datetime					SELECT @billdate_eEx = ISNULL(ParaValue,'') FROM @dynTable WHERE ParaField = 'billdate_e'
DECLARE @definetypeEx NVARCHAR(60)				SELECT @definetypeEx = ISNULL(ParaValue,'') FROM @dynTable WHERE ParaField = 'definetype'
DECLARE @definenameEx NVARCHAR(60)				SELECT @definenameEx = ISNULL(ParaValue,'') FROM @dynTable WHERE ParaField = 'definename'
DECLARE @ptypeidEx NVARCHAR(60)					SELECT @ptypeidEx = ISNULL(ParaValue,'') FROM @dynTable WHERE ParaField = 'ptypeid'
DECLARE @ptypecategoryEx NVARCHAR(50)			SELECT @ptypecategoryEx = ISNULL(ParaValue,'1') FROM @dynTable WHERE ParaField = 'ptypecategory'
DECLARE @pcrecEx int							SELECT @pcrecEx = ISNULL(ParaValue,'') FROM @dynTable WHERE ParaField = 'pcrec'
DECLARE @psrecEx int							SELECT @psrecEx = ISNULL(ParaValue,'') FROM @dynTable WHERE ParaField = 'psrec'
DECLARE @dlistfieldEx NVARCHAR(200)				SELECT @dlistfieldEx = ISNULL(ParaValue,'') FROM @dynTable WHERE ParaField = 'dlistfield'
DECLARE @containsstopEx bit						SELECT @containsstopEx = ISNULL(ParaValue,'') FROM @dynTable WHERE ParaField = 'containsstop'
DECLARE @ddistdetailfieldEx NVARCHAR(200)		SELECT @ddistdetailfieldEx = ISNULL(ParaValue,'') FROM @dynTable WHERE ParaField = 'ddistdetailfield'
DECLARE @assist1Ex int							SELECT @assist1Ex = ParaValue FROM @dynTable WHERE ParaField = 'assist1'
DECLARE @assist2Ex int 							SELECT @assist2Ex = ParaValue FROM @dynTable WHERE ParaField = 'assist2'
DECLARE @assist3Ex int 							SELECT @assist3Ex = ParaValue FROM @dynTable WHERE ParaField = 'assist3'
DECLARE @assist4Ex int 							SELECT @assist4Ex = ParaValue FROM @dynTable WHERE ParaField = 'assist4'
DECLARE @assist5Ex int							SELECT @assist5Ex = ParaValue FROM @dynTable WHERE ParaField = 'assist5'
DECLARE @assist6Ex int 							SELECT @assist6Ex = ParaValue FROM @dynTable WHERE ParaField = 'assist6'
DECLARE @assist7Ex int 							SELECT @assist7Ex = ParaValue FROM @dynTable WHERE ParaField = 'assist7'
DECLARE @assist8Ex int 							SELECT @assist8Ex = ParaValue FROM @dynTable WHERE ParaField = 'assist8'
DECLARE @opridEx nvarchar(50)					SELECT @opridEx = ISNULL(ParaValue,'') FROM @dynTable WHERE ParaField = 'oprid'

DECLARE @ptypecategory_ VARCHAR(50)
SET @ptypecategory_ = 'ptypeid1'
SET @ptypecategoryEx = ISNULL(@ptypecategoryEx,'1')
SELECT @ptypecategory_ = @ptypecategory_+','+'ptypeid'+CAST(orderid AS VARCHAR) FROM Fn_splitWithOrderid(@ptypecategoryEx,',') WHERE orderid > 1
SET @dlistfieldEx = REPLACE(@dlistfieldEx,'ptypecategory',@ptypecategory_)
	
--设置查询字段
DECLARE @ShowFields         VARCHAR(5000)		SET @ShowFields   		= CASE WHEN (@ddistdetailfieldEx IS NULL OR @ddistdetailfieldEx = '') THEN @dlistfieldEx ELSE @dlistfieldEx+','+@ddistdetailfieldEx END 
DECLARE @Ptypeid            VARCHAR(100) 		SET @Ptypeid      		= REPLACE(@ptypeidEx,'%','')
DECLARE @ctypeid			VARCHAR(100)		SET @ctypeid     		= REPLACE(@branchidEx,'%','')
DECLARE @KtypeId   			VARCHAR(50) 		SET @Ktypeid      		= REPLACE(@ktypeidEx,'%','')
DECLARE @Sizeid				INT					SET @Sizeid       		= REPLACE(@psrecEx,'%','')
DECLARE @Colorid			INT					SET @Colorid      		= REPLACE(@pcrecEx,'%','')
DECLARE @BillDate_s         VARCHAR(12)			SET @BillDate_s   		= CONVERT(VARCHAR(10),@billdate_sEx,23)
DECLARE @BillDate_e         VARCHAR(12)			SET @BillDate_e   		= CONVERT(VARCHAR(10),@billdate_eEx,23)
DECLARE @NowDate			VARCHAR(12)			SET @NowDate 			= CONVERT(VARCHAR(10),GETDATE(),23)
DECLARE @CustDefValue       VARCHAR(50) 		SET @CustDefValue 		= REPLACE(@definenameEx,'%','')
DECLARE @Assist1            VARCHAR(10) 		SET @Assist1      		= @assist1Ex
DECLARE @Assist2            VARCHAR(10)			SET @Assist2      		= @assist2Ex
DECLARE @Assist3            VARCHAR(10)			SET @Assist3      		= @assist3Ex
DECLARE @Assist4            VARCHAR(10)			SET @Assist4      		= @assist4Ex
DECLARE @Assist5            VARCHAR(10)			SET @Assist5      		= @assist5Ex
DECLARE @Assist6            VARCHAR(10)			SET @Assist6      		= @assist6Ex
DECLARE @Assist7            VARCHAR(10)			SET @Assist7      		= @assist7Ex
DECLARE @Assist8            VARCHAR(10)			SET @Assist8      		= @assist8Ex
DECLARE @ISContainStop		INT 				SET @IsContainStop		= CONVERT(INT ,@containsstopEx)
DECLARE @OperatorId         VARCHAR(50)			SET @OperatorID   		= @opridEx
												
DECLARE @GroupBy VARCHAR(5000),@SQLCommond VARCHAR(8000),@WhereCmd VARCHAR(2000),@NeedAssist BIT,@SQLText  VARCHAR(8000),@Group VARCHAR(5000),@PKFields VARCHAR(5000),@aaGroup VARCHAR(5000),@aaPKFields VARCHAR(5000),@bbPKFields VARCHAR(5000),@Fields VARCHAR(5000)
declare @Where VARCHAR(2000),@ReWhere VARCHAR(2000),@days  VARCHAR(10)
if @ctypeid=''
	SELECT @days=count(branchid) from branch where sonnum=0 and deleted=0
else 
	SELECT @days=count(branchid) from branch where sonnum=0 and  branchid like @ctypeid+'%'

SET @ReWhere=''
SET @SQLText='
IF OBJECT_ID(''''tempdb..#TempTableBillIndex'''') IS NOT NULL 
	DROP TABLE #TempTableBillIndex  
        
SELECT d.ptypeid,ds.qty,d.date,ds.sizeid,ds.colorid,d.branchid,d.ktypeid,ds.bargaintotal total,
left(D.ptypeid,@N1*5) ptypeid1,
left(D.ptypeid,@N2*5) ptypeid2,
left(D.ptypeid,@N3*5) ptypeid3
'

IF(CHARINDEX(',startdate,',','+@ddistdetailfieldEx+',')>0)
	SET @SQLText = @SQLText+',issueDate'
IF(CHARINDEX(',enddate,',','+@ddistdetailfieldEx+',')>0)
	SET @SQLText = @SQLText+',stopDate'
IF(CHARINDEX(',assist1,',','+@dlistfieldEx+',')>0)
	SET @SQLText = @SQLText+',assist1'
IF(CHARINDEX(',assist2,',','+@dlistfieldEx+',')>0)
	SET @SQLText = @SQLText+',assist2'
IF(CHARINDEX(',assist3,',','+@dlistfieldEx+',')>0)
	SET @SQLText = @SQLText+',assist3'
IF(CHARINDEX(',assist4,',','+@dlistfieldEx+',')>0)
	SET @SQLText = @SQLText+',assist4'
IF(CHARINDEX(',assist5,',','+@dlistfieldEx+',')>0)
	SET @SQLText = @SQLText+',assist5'
IF(CHARINDEX(',assist6,',','+@dlistfieldEx+',')>0)
	SET @SQLText = @SQLText+',assist6'
IF(CHARINDEX(',assist7,',','+@dlistfieldEx+',')>0)
	SET @SQLText = @SQLText+',assist7'
IF(CHARINDEX(',assist8,',','+@dlistfieldEx+',')>0)
	SET @SQLText = @SQLText+',assist8'
	
SET @SQLText = @SQLText+'
INTO #TempTableBillIndex 
from dbo.DlyData d 
INNER join dbo.DlyDataDetail ds on d.dlyorder = ds.dlyorder
INNER JOIN #PListTemp on #PListTemp.TypeID = D.ptypeid
__AssistTables__
where d.vchtype IN (12,100)
and d.redold=''''F''''
and d.Date between '''''+@BillDate_s+'''''  and '''''+@BillDate_e+'''''
AND EXISTS (select 1 from #KListTemp WHERE #KListTemp.TypeID = d.KtypeId)	--仓库多级权限 
AND (@containsstop = 1 OR #PListTemp.STOP=@containsstop)
__AssistWheres__
'


if @ctypeid<>''
BEGIN
	SELECT @SQLText=@SQLText+' 
and d.branchid like '''''+@ctypeid+'%'''''
END 
IF @Ptypeid <> ''
BEGIN
	SELECT @SQLText=@SQLText + ' 
AND d.PtypeId LIKE '''''+ @ptypeid+'%'''''
END
IF @Ktypeid<>''
	SELECT @SQLText=@SQLText + ' 
and d.KtypeId like '''''+@Ktypeid+'%'''''

if @colorID<>0
BEGIN
	SET @SQLText=@SQLText+' 
and ds.colorId=' + CAST( @colorID AS VARCHAR(10) )
END 
if @sizeID<>0
BEGIN
	SET @SQLText=@SQLText+'  
and ds.sizeId=' + CAST( @sizeID AS VARCHAR(10) ) 
END 
IF @CustDefValue <>''
BEGIN
SET @SQLText = @SQLText +' 
and (custvalue1 ='''''+@CustDefValue+''''' or custvalue2 ='''''+@CustDefValue+''''' or custvalue3 ='''''+@CustDefValue+''''' or custvalue4 ='''''+@CustDefValue+''''' or custvalue5 ='''''+@CustDefValue+''''' or custvalue6 ='''''+@CustDefValue+''''')'
END

SET @Fields=''
SET @Group=''
SET @GroupBy = ''
SET @WhereCmd = ''
SET @Where= ''
SET @SQLCommond=''
SET @PKFields=''
SET @aaPKFields=''
SET @bbPKFields=''
SET @aaGroup=''
/*****
替换字段表达式
*******/
if @ShowFields is null or @ShowFields=''
BEGIN
	SET @Fields=@Fields+'a.ptypeid'
END
else
BEGIN
SET @Fields=@Fields+'a.ptypeid'
IF CHARINDEX('branchid',@ShowFields)>0
BEGIN
	SET @Fields = @Fields+',a.branchid'	
	SET @GroupBy = @GroupBy+',a.branchid'
	SET  @PKFields=@PKFields+',k.branchid'
	SET @Group = @Group+',k.branchid'
	SET  @aaPKFields=@aaPKFields+',branchid'
	SET @aaGroup = @aaGroup+',branchid'
	SET @WhereCmd =@WhereCmd+' and a.branchid=d.branchid'
	SET @Where=@Where+' and a.branchid=b.branchid'
END

IF CHARINDEX('colorid',@ShowFields)>0
BEGIN
	SET @Fields = @Fields+',RIGHT(''''00000''''+ CAST(a.ColorID AS VARCHAR),5) colorid'
	
	SET @GroupBy = @GroupBy+',a.colorid'
	SET  @PKFields=@PKFields+',t.colorid'
	SET @Group = @Group+',t.colorid'
	SET  @aaPKFields=@aaPKFields+',colorid'
	SET @aaGroup = @aaGroup+',colorid'
	SET @Where=@Where+' and a.colorid=b.colorid'
	SET @WhereCmd =@WhereCmd+' and a.colorid=d.colorid'
	
END
IF CHARINDEX('sizeid',@ShowFields)>0
BEGIN
	SET @Fields = @Fields+',RIGHT(''''00000''''+ CAST(a.sizeid AS VARCHAR),5) sizeid'
	SET @GroupBy = @GroupBy+',a.sizeid'
	SET  @PKFields=@PKFields+',t.sizeid'
	SET @Group = @Group+',t.sizeid'
	SET  @aaPKFields=@aaPKFields+',sizeid'
	SET @aaGroup = @aaGroup+',sizeid'
	SET @Where=@Where+' and a.sizeid=b.sizeid'
	SET @WhereCmd =@WhereCmd+' and a.sizeid=d.sizeid'
END

IF CHARINDEX('ktypeid',@ShowFields)>0
BEGIN
	SET @Fields = @Fields+',a.ktypeid'
	SET @GroupBy = @GroupBy+',a.ktypeid'
	SET  @PKFields=@PKFields+',s.ktypeid'
	SET @Group = @Group+',s.ktypeid'
	SET  @aaPKFields=@aaPKFields+',ktypeid'
	SET @aaGroup = @aaGroup+',ktypeid'
	SET @Where=@Where+' and a.ktypeid=b.ktypeid'
	SET @WhereCmd =@WhereCmd+' and a.ktypeid=d.ktypeid'
END
IF CHARINDEX('startdate',@ShowFields)>0
BEGIN
	SET @Fields = @Fields+',a.issueDate startdate' 
	SET @GroupBy = @GroupBy+',a.issueDate'
END
IF CHARINDEX('enddate',@ShowFields)>0
BEGIN
	SET @Fields = @Fields+',a.stopDate enddate' 
	SET @GroupBy = @GroupBy+',a.stopDate'
END
IF CHARINDEX('nowdate',@ShowFields)>0
BEGIN
	SET @Fields = @Fields+','''''+@NowDate+'''''  nowdate' 
END
IF CHARINDEX('maxqty',@ShowFields)>0
BEGIN
	SET @Fields = @Fields+',d.maxqty  maxqty' 
	SET @GroupBy = @GroupBy+',d.maxqty'
	
END
IF CHARINDEX('maxsaledate',@ShowFields)>0
BEGIN
	SET @Fields = @Fields+',d.maxsaledate  maxsaledate' 
	SET @GroupBy = @GroupBy+',d.maxsaledate'
	
END
IF CHARINDEX('saleqty',@ShowFields)>0
BEGIN
	SET @Fields = @Fields+'
,sum(isnull(-a.qty,0))  saleqty' 
END
IF CHARINDEX('saletotal',@ShowFields)>0
BEGIN
	SET @Fields = @Fields+'
,sum(isnull(-a.total,0))  saletotal' 
END
IF CHARINDEX('avgdayqty',@ShowFields)>0
BEGIN
	SET @Fields = @Fields+'
, ROUND(CAST(sum(isnull(-a.qty,0)) AS NUMERIC(24,10))/@D1,@dig_qty)  avgdayqty' 
END
IF CHARINDEX('avgstoreqty',@ShowFields)>0
BEGIN
	SET @Fields = @Fields+'
, case when '+@days+' = 0 then 0 else ROUND(CAST(sum(isnull(-a.qty,0)) AS NUMERIC(24,10))/CAST('+@days+' AS NUMERIC(24,10)),@dig_qty) end avgstoreqty'
END
--IF CHARINDEX('stockqty',@ShowFields)>0
--BEGIN
	SET @Fields = @Fields+',b.stockqty  stockqty' 
	SET @GroupBy = @GroupBy+',b.stockqty'
--END
IF CHARINDEX('daysqty',@ShowFields)>0
BEGIN
	SET @Fields = @Fields+'
,case when sum(isnull(-a.qty,0))=0 or ROUND(CAST(sum(isnull(-a.qty,0)) AS NUMERIC(24,10))/@D1,@dig_qty)=0 then 0 
      else  b.stockqty/ROUND(CAST(sum(isnull(-a.qty,0)) AS NUMERIC(24,10))/@D1,@dig_qty)END daysqty' 
END

END

SET @SQLCommond = ''


--查询字段,查询条件,查询表,分组字段,最终排序字段
DECLARE @AssistTables VARCHAR(MAX),@AssistWheres VARCHAR(MAX)

--设置查询条件
--设置查询表
SET @AssistTables = ''
SET @AssistWheres = ''
BEGIN
	IF(CHARINDEX(',assist1,',','+@dlistfieldEx+',')>0)
	BEGIN
		SET @AssistTables = @AssistTables + '
	LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist1,gg.AttributeID FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh ON hh.AttributeId = gg.AttributeID AND TypeID = 1) A1 ON A1.PtypeId = d.PtypeId AND (@assist1 IS NULL OR A1.AttributeID = @assist1)'
		SET @AssistWheres = @AssistWheres+'
	AND (A1.PtypeId IS NOT NULL OR @assist1 IS NULL)'
	END
	ELSE IF @assist1 IS NOT NULL
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = @assist1))'
	END
	IF(CHARINDEX(',assist2,',','+@dlistfieldEx+',')>0)
	BEGIN
		SET @AssistTables = @AssistTables + '
	LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist2,gg.AttributeID FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh ON hh.AttributeId = gg.AttributeID AND TypeID = 2) A2 ON A2.PtypeId = d.PtypeId AND (@assist2 IS NULL OR A2.AttributeID = @assist2)'
		SET @AssistWheres = @AssistWheres+'
	AND (A2.PtypeId IS NOT NULL OR @assist2 IS NULL)'
	END
	ELSE IF @assist2 IS NOT NULL
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = @assist2))'
	END
	IF(CHARINDEX(',assist3,',','+@dlistfieldEx+',')>0)
	BEGIN
		SET @AssistTables = @AssistTables + '
	LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist3,gg.AttributeID FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh ON hh.AttributeId = gg.AttributeID AND TypeID = 3) A3 ON A3.PtypeId = d.PtypeId AND (@assist3 IS NULL OR A3.AttributeID = @assist3)'
		SET @AssistWheres = @AssistWheres+'
	AND (A3.PtypeId IS NOT NULL OR @assist3 IS NULL)'
	END
	ELSE IF @assist3 IS NOT NULL
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = @assist3))'
	END
	IF(CHARINDEX(',assist4,',','+@dlistfieldEx+',')>0)
	BEGIN
		SET @AssistTables = @AssistTables + '
	LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist4,gg.AttributeID FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh ON hh.AttributeId = gg.AttributeID AND TypeID = 4) A4 ON A4.PtypeId = d.PtypeId AND (@assist4 IS NULL OR A4.AttributeID = @assist4)'
		SET @AssistWheres = @AssistWheres+'
	AND (A4.PtypeId IS NOT NULL OR @assist4 IS NULL)'
	END
	ELSE IF @assist4 IS NOT NULL
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = @assist4))'
	END
	IF(CHARINDEX(',assist5,',','+@dlistfieldEx+',')>0)
	BEGIN
		SET @AssistTables = @AssistTables + '
	LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist5,gg.AttributeID FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh ON hh.AttributeId = gg.AttributeID AND TypeID = 5) A5 ON A5.PtypeId = d.PtypeId AND (@assist5 IS NULL OR A5.AttributeID = @assist5)'
		SET @AssistWheres = @AssistWheres+'
	AND (A5.PtypeId IS NOT NULL OR @assist5 IS NULL)'
	END
	ELSE IF @assist5 IS NOT NULL
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = @assist5))'
	END
	IF(CHARINDEX(',assist6,',','+@dlistfieldEx+',')>0)
	BEGIN
		SET @AssistTables = @AssistTables + '
	LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist6,gg.AttributeID FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh ON hh.AttributeId = gg.AttributeID AND TypeID = 6) A6 ON A6.PtypeId = d.PtypeId AND (@assist6 IS NULL OR A6.AttributeID = @assist6)'
		SET @AssistWheres = @AssistWheres+'
	AND (A6.PtypeId IS NOT NULL OR @assist6 IS NULL)'
	END
	ELSE IF @assist6 IS NOT NULL
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = @assist6))'
	END
	IF(CHARINDEX(',assist7,',','+@dlistfieldEx+',')>0)
	BEGIN
		SET @AssistTables = @AssistTables + '
	LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist7,gg.AttributeID FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh ON hh.AttributeId = gg.AttributeID AND TypeID = 7) A7 ON A7.PtypeId = d.PtypeId AND (@assist7 IS NULL OR A7.AttributeID = @assist7)'
		SET @AssistWheres = @AssistWheres+'
	AND (A7.PtypeId IS NOT NULL OR @assist7 IS NULL)'
	END
	ELSE IF @assist7 IS NOT NULL
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = @assist7))'
	END
	IF(CHARINDEX(',assist8,',','+@dlistfieldEx+',')>0)
	BEGIN
		SET @AssistTables = @AssistTables + '
	LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist8,gg.AttributeID FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh ON hh.AttributeId = gg.AttributeID AND TypeID = 8) A8 ON A8.PtypeId = d.PtypeId AND (@assist8 IS NULL OR A8.AttributeID = @assist8)'
		SET @AssistWheres = @AssistWheres+'
	AND (A8.PtypeId IS NOT NULL OR @assist8 IS NULL)'
	END
	ELSE IF @assist8 IS NOT NULL
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = @assist8))'
	END
END

SET @GroupBy = @GroupBy+','
BEGIN
	IF(CHARINDEX(',assist1,',','+@dlistfieldEx+',')>0)
		SET @GroupBy = @GroupBy+'assist1,'
	IF(CHARINDEX(',assist2,',','+@dlistfieldEx+',')>0)
		SET @GroupBy = @GroupBy+'assist2,'
	IF(CHARINDEX(',assist3,',','+@dlistfieldEx+',')>0)
		SET @GroupBy = @GroupBy+'assist3,'
	IF(CHARINDEX(',assist4,',','+@dlistfieldEx+',')>0)
		SET @GroupBy = @GroupBy+'assist4,'
	IF(CHARINDEX(',assist5,',','+@dlistfieldEx+',')>0)
		SET @GroupBy = @GroupBy+'assist5,'
	IF(CHARINDEX(',assist6,',','+@dlistfieldEx+',')>0)
		SET @GroupBy = @GroupBy+'assist6,'
	IF(CHARINDEX(',assist7,',','+@dlistfieldEx+',')>0)
		SET @GroupBy = @GroupBy+'assist7,'
	IF(CHARINDEX(',assist8,',','+@dlistfieldEx+',')>0)
		SET @GroupBy = @GroupBy+'assist8,'
	IF(CHARINDEX(',ptypeid1,',','+@dlistfieldEx+',')>0)
		SET @GroupBy = @GroupBy+'ptypeid1,'
	IF(CHARINDEX(',ptypeid2,',','+@dlistfieldEx+',')>0)
		SET @GroupBy = @GroupBy+'ptypeid2,'
	IF(CHARINDEX(',ptypeid3,',','+@dlistfieldEx+',')>0)
		SET @GroupBy = @GroupBy+'ptypeid3,'	
END

SET @SQLText = REPLACE(@SQLText,'__AssistTables__',		@AssistTables)
SET @SQLText = REPLACE(@SQLText,'__AssistWheres__',		@AssistWheres)

SET @GroupBy = SUBSTRING(@GroupBy,1,LEN(@GroupBy)-1)
						
SET @SQLCmd1 ='	
IF(@ptypecategory = '''''''' OR @ptypecategory IS NULL)
	SET @ptypecategory = ''''1''''
								
DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int ,@N1 TINYINT,@N2 TINYINT,@N3 TINYINT,@D1 NUMERIC(24,10)
EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 

SELECT @N1=a*5 FROM Fn_splitWithOrderid(@ptypecategory,'''','''') WHERE orderid = 1
SELECT @N2=a*5 FROM Fn_splitWithOrderid(@ptypecategory,'''','''') WHERE orderid = 2
SELECT @N3=a*5 FROM Fn_splitWithOrderid(@ptypecategory,'''','''') WHERE orderid = 3
SET @D1 = CAST((datediff(dd,'''''+@BillDate_s+''''','''''+@BillDate_e+''''')+1) AS NUMERIC(24,10))
/***********************************************************************/

--仓库多级权限
IF(OBJECT_ID(''''tempdb..#KListTemp'''') IS NOT NULL)
	DROP TABLE #KListTemp
SELECT KtypeId AS TypeID INTO #KListTemp FROM dbo.FN_GetStockListOfBranch(@oprid,'''''''','''''''')

--商品多级权限
IF(OBJECT_ID(''''tempdb..#PListTemp'''') IS NOT NULL)
	DROP TABLE #PListTemp
SELECT TypeID,[stop],issueDate,stopDate INTO #PListTemp FROM dbo.FN_GetPowerRangePList(@oprid,'''''''')
CREATE CLUSTERED INDEX IX_GoodsRetailTotal_PListTemp_Typeid ON #PListTemp (TypeID)


'+@SQLText+'
/***********************************************************************/
IF OBJECT_ID(''''tempdb..#table_S'''') IS NOT NULL 
        DROP TABLE #table_S  

SELECT ptypeid,sum(-qty) qty,date ______aaPKFields______
into #table_S
		from #TempTableBillIndex
		group by ptypeid,date ______aaGroup______

IF object_id(''''tempdb..#tmpsort'''') is not null
                drop table #tmpsort
SELECT tmpsort.* INTO #tmpsort
FROM ( 
-------------------------------------------------------------------------
SELECT ______@Fields______,0 as saleqtyexpand
from #TempTableBillIndex a 
LEFT join		
(	
	SELECT ISNULL(sum(t.qty),0) stockqty,s.ptypeid ptypeid______PKFields______
	from  goodsstockdetail t,goodsstocks s, stock k
	where t.orderid=s.orderid and k.typeid=s.ktypeid 
	AND EXISTS (select 1 from #KListTemp WHERE #KListTemp.TypeID = s.ktypeid)	--仓库多级权限 
	AND EXISTS (select 1 from #PListTemp WHERE #PListTemp.TypeID = S.ptypeid AND (@containsstop = 1 OR #PListTemp.STOP=@containsstop))
	and k.typeid like '''''+@Ktypeid+'%''''
	and k.branchid like '''''+@ctypeid+'%''''
	group by s.ptypeid ______Group______                                        
) b  on b.ptypeid=a.ptypeid  ______Where______
INNER join
(
	SELECT ptypeid,max(qty) maxqty
	,(SELECT top 1 date from #table_S a where a.qty=max(b.qty) and a.ptypeid=b.ptypeid  ______Where______) as maxsaledate
	 ______aaPKFields______
	from #table_S b
	group by ptypeid  ______aaGroup______
) d on a.ptypeid=d.ptypeid ______WhereCmd______

group by a.ptypeid_____groupBy______	
-------------------------------------------------------------------------
) tmpsort; 

/*最终结果表*/
with Data AS (
SELECT * FROM #tmpsort
),'


IF(CHARINDEX(',assist1,',','+@dlistfieldEx+',')>0)
	SET @Fields = @Fields+',assist1'
IF(CHARINDEX(',assist2,',','+@dlistfieldEx+',')>0)
	SET @Fields = @Fields+',assist2'
IF(CHARINDEX(',assist3,',','+@dlistfieldEx+',')>0)
	SET @Fields = @Fields+',assist3'
IF(CHARINDEX(',assist4,',','+@dlistfieldEx+',')>0)
	SET @Fields = @Fields+',assist4'
IF(CHARINDEX(',assist5,',','+@dlistfieldEx+',')>0)
	SET @Fields = @Fields+',assist5'
IF(CHARINDEX(',assist6,',','+@dlistfieldEx+',')>0)
	SET @Fields = @Fields+',assist6'
IF(CHARINDEX(',assist7,',','+@dlistfieldEx+',')>0)
	SET @Fields = @Fields+',assist7'
IF(CHARINDEX(',assist8,',','+@dlistfieldEx+',')>0)
	SET @Fields = @Fields+',assist8'
IF(CHARINDEX(',ptypeid1,',','+@dlistfieldEx+',')>0)
	SET @Fields = @Fields+',ptypeid1'
IF(CHARINDEX(',ptypeid2,',','+@dlistfieldEx+',')>0)
	SET @Fields = @Fields+',ptypeid2'
IF(CHARINDEX(',ptypeid3,',','+@dlistfieldEx+',')>0)
	SET @Fields = @Fields+',ptypeid3'	

SET @SQLCmd1 = REPLACE(@SQLCmd1,'______@Fields______'		,@Fields)
SET @SQLCmd1 = REPLACE(@SQLCmd1,'______PKFields______'		,@PKFields)
SET @SQLCmd1 = REPLACE(@SQLCmd1,'______aaPKFields______'	,@aaPKFields)
SET @SQLCmd1 = REPLACE(@SQLCmd1,'______Group______'			,@Group)
SET @SQLCmd1 = REPLACE(@SQLCmd1,'______WhereCmd______'		,@WhereCmd)
SET @SQLCmd1 = REPLACE(@SQLCmd1,'______Where______'			,@Where)
SET @SQLCmd1 = REPLACE(@SQLCmd1,'______aaGroup______'		,@aaGroup)
SET @SQLCmd1 = REPLACE(@SQLCmd1,'_____groupBy______'		,@GroupBy)


SET @GroupBy = REPLACE(@GroupBy,'a.','') 
SET @GroupBy = REPLACE(@GroupBy,'b.','') 
SET @GroupBy = REPLACE(@GroupBy,'p.','') 
SET @GroupBy = REPLACE(@GroupBy,'d.','') 
SET @GroupBy = REPLACE(@GroupBy,',',',DATA.')
SET @GroupBy = REPLACE(@GroupBy,'issueDate','startdate')
SET @GroupBy = REPLACE(@GroupBy,'stopDate','enddate')

-- 排序信息
declare @sortInfo varchar(255) = isnull((select ParaValue from @dynTable where ParaField = '__SortInfo__') + ',', '')
-- 排序联接信息
declare @sortJoinInfo varchar(555) = isnull((select replace(ParaValue, '__LeftTable__', 'Data') from @dynTable where ParaField = '__SortJoinInfo__'), '')
	
set @sqlCmd = cast(
(
	@SQLCmd1
	+ '
	__ReportData__ AS (
	select dense_rank() over (order by ' + @sortInfo +'DATA.ptypeid'+ @GroupBy + ' desc) __RowNo__,DATA.*
	from Data ' + @sortJoinInfo + ')'
) as nvarchar(max))

END

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


--  ********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：F_S_GetSYSsz                                          
--  ||   过程功能：系统设置－－系统配置（读）  
--  ||=========================================================================================  
--  ||   参数说明：  参数名称         类型            意义                     输入输出  
--  ||            -----------------------------------------------------------------------------  
--  ||        @szValue*   varchar(100)                 写入对应的单位设置值  
--  ||=========================================================================================     
--  ||   返回值：         值                                     说明  
--  ||       ----------------------------------------------------------------------------------------  
--  ||                    0                                 执行成功  
--  ||                  －1                               执行失败  
--  ||==========================================================================================  
CREATE  PROCEDURE FZGetSYS  
(            @subValue1   varchar(100) output,--是否使用同一成本算法：－1不使用统一成本算法，0:加权平均法，1:先进先出法，2:后进先出法，3:手工指定法  
             @subValue2   varchar(100) output,--设定价格管理方式0：统一零售价多折扣，1：多价格管理方式  
             @subValue3   varchar(100) output,--业务单据录入行数  
             @subValue4   varchar(100) output,--系统自动备份天数  
             @subValue5   varchar(100) output,--数量小数位数配置  
             @subValue6  varchar(100) output,--单价小数位数配置  
             @subValue7   varchar(100) output,--金额小数位数配置  
             @subValue8 varchar(100) output,--税率小数位数配置  
             @subValue9 varchar(100) output,--折扣小数位数配置  
             @subValue10 varchar(1)  output,  --是否截屏  
             @subValue11 varchar(100) output,--  
             @subValue12 varchar(100) output,--  
             @subValue13 varchar(100) output,--  
             @subValue14 varchar(1)  output,  --  
             @subValue15 varchar(100) output,--  
             @subValue16 varchar(100) output,--  
             @subValue17 varchar(100) output,  
             @subValue18 varchar(1) output,--数量启用小数  
             @subValue19 varchar(1) output,--扣率启用小数  
             @subvalue20 varchar(1) output,  
             @subvalue21 varchar(100) output, --商品唯一码位数
             @subvalue22 varchar(100) output, --加盟商配货单机构权限设置
             @subvalue23 varchar(100) output, --内部配货单机构权限设置 
             @subvalue24 varchar(100) OUTPUT,  --启用POS
             @subvalue25 varchar(1) OUTPUT,  --是否启用唯一码
             @subvalue26 varchar(1) OUTPUT,  --唯一码管理方式
             @subvalue27 varchar(1) OUTPUT,  --是否启用退货价跟踪
             @subvalue28 varchar(1) OUTPUT,  --商品录入方式选择:0=启用配码，1=启用双单位
             @subvalue29 varchar(100) output,  --配货申请单机构权限设置
             @subvalue30 varchar(100) output,  --启用店账通
             @subvalue31 varchar(100) output,  --启用订货会
             @subvalue32 varchar(1) output,  --启用IC卡设备
             @subvalue33 varchar(100) output,  --IC卡设备会员卡标识
             @subvalue34 varchar(100) output  --IC卡设备名称
)  
AS  
selectSysdata:  
       select @subvalue1 =(select subvalue From [sysdata]  Where subname='usesamecostmode')  
       if @subvalue1<>0 and exists( select 1 from syscon where  [stats]=1 and [order]=106)  
       Begin  
     update syscon set [stats]=0 where [order]=106  
       end  
       select @subvalue2 =(select subvalue From [sysdata]  Where subname='unitedisctax')  
       select @subvalue3 =(select subvalue From [sysdata]  Where subname='billrow')  
       select @subvalue4 =(select subvalue From [sysdata]  Where subname='autobakupdays')  
       select @subvalue5 =(select subvalue From [sysdata]  Where subname='DecimalQty')  
       select @subvalue6 =(select subvalue From [sysdata]  Where subname='DecimalPrice')  
       select @subvalue7 =(select subvalue From [sysdata]  Where subname='DecimalTotal')  
       select @subvalue8 =(select subvalue From [sysdata]  Where subname='DecimalTaxRate')  
       select @subvalue9 =(select subvalue From [sysdata]  Where subname='DecimalDiscount')  
       select @subvalue10 =(select subvalue From [sysdata]  Where subname='CanPrintScreen')  
       select @subvalue11 =(select subvalue From [sysdata]  Where subname='RETAIL_BTYPE_ID')  
       select @subvalue12 =(select subvalue From [sysdata]  Where subname='RETAIL_KTYPE_ID')  
       select @subvalue13 =(select subvalue From [sysdata]  Where subname='RETAIL_ATYPE_ID')  
       select @subvalue14 =(select subvalue From [sysdata]  Where subname='CashAsBillMoney')  
       select @subvalue15 =(select subvalue From [sysdata]  Where subname='RETAIL_BTYPE_NAME')  
       select @subvalue16 =(select subvalue From [sysdata]  Where subname='RETAIL_KTYPE_NAME')  
       select @subvalue17 =(select subvalue From [sysdata]  Where subname='RETAIL_ATYPE_NAME')  
       select @subvalue18 =(select subvalue From [sysdata]  Where subname='IfDecimalQty')  
       select @subvalue19 =(select subvalue From [sysdata]  Where subname='IfDecimalDiscount')  
       select @subvalue20 =(select subvalue From [sysdata]  Where subname='posPayConfig')  
       select @subvalue21 =(select subvalue From [sysdata]  Where subname='PtypeUniqueSet')  
       select @subvalue22 =(select subvalue from [sysdata] where subname='JMSLimit')
       select @subvalue23 =(select subvalue from [sysdata] where subname='NBPHLimit')
       select @subvalue24 =(select subvalue from [sysdata] where subname='usepos')
       select @subvalue25 =(select subvalue from [sysdata] where subname='useUnique')
       select @subvalue26 =(select subvalue from [sysdata] where subname='UniqueManageType')
       select @subvalue27 =(select subvalue from [sysdata] where subname='tailBackPrice')
       select @subvalue28 =(select subvalue from [sysdata] where subname='goodsInputStyle')
       select @subvalue29 =(select subvalue from [sysdata] where subname='PHSQLimit')
       select @subvalue30 =(select subvalue from [sysdata] where subname='BoolDZT')
       select @subvalue31 =(select subvalue from [sysdata] where subname='mposetting')
       select @subvalue32 =(select subvalue from [sysdata] where subname='IsVipICCard')
       select @subvalue33 =(select subvalue from [sysdata] where subname='ICCardMark')
       select @subvalue34 =(select subvalue from [sysdata] where subname='VipICMachine')
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZSetSYSsz]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZSetSYSsz]
GO


--  ********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：F_S_SetSYSsz                                          
--  ||   过程功能：系统设置－－系统配置  
--  ||=========================================================================================  
--  ||   参数说明：  参数名称         类型            意义                     输入输出  
--  ||            -----------------------------------------------------------------------------  
--  ||        @szValue*   varchar(100)                 写入对应的单位设置值  
--  ||=========================================================================================     
--  ||   返回值：         值                                     说明  
--  ||       ----------------------------------------------------------------------------------------  
--  ||                    0                                 执行成功  
--  ||                  －1                               执行失败  
--  ||==========================================================================================  
CREATE   PROCEDURE FZSetSYSsz
    (
      @szValue1 VARCHAR(100),--是否使用同一成本算法：－1不使用统一成本算法，0:加权平均法，1:先进先出法，2:后进先出法，3:手工指定法  
      @szValue2 VARCHAR(100),--统一折扣和税率：0：统一零售价多折扣，1：多价格管理方式  
      @szValue3 VARCHAR(100),--业务单据录入行数  
      @szValue4 VARCHAR(100),--系统自动备份天数  
      @szValue5 VARCHAR(100),--数量小数位数配置  
      @szValue6 VARCHAR(100),--单价小数位数配置  
      @szValue7 VARCHAR(100),--金额小数位数配置  
      @szValue8 VARCHAR(100),--税率小数位数配置  
      @szValue9 VARCHAR(100),--折扣小数位数配置  
      @szValue10 VARCHAR(1),
      @szValue11 VARCHAR(1),--数量启用小数  
      @szValue12 VARCHAR(1),--扣率启用小数  
      @szValue13 VARCHAR(1),  --pos结算配置	     
      @szValue14 VARCHAR(100),--商品唯一码小数位数设置
      @szValue15 VARCHAR(100),--加盟商配货单权限设置
      @szValue16 VARCHAR(100),--内部配货单权限设置
      @szValue17 VARCHAR(100),--是否启用POS管理
      @szValue18 VARCHAR(1),--是否启用唯一码
      @szValue19 VARCHAR(1),--唯一码管理方式
      @szValue20 VARCHAR(1),--是否启用退货价跟踪
      @szValue21 VARCHAR(1),--商品录入方式选择:0=启用配码，1=启用双单位
      @szValue22 VARCHAR(100),--配货申请单权限设置
      @szValue23 VARCHAR(100),--是否启用店账通
      @szValue24 VARCHAR(100),--OA消息间隔
      @szValue25 VARCHAR(100),--指定用户数
      @szValue26 VARCHAR(100),-- 产品名称
      @szValue27 VARCHAR(100),-- 是否启用订货会
      @szValue28 VARCHAR(1),--启用IC卡设备
      @szValue29 VARCHAR(100),-- IC卡设备会员卡标识
      @szValue30 VARCHAR(100),-- IC卡设备名称
      @modifydig INT = 0 OUT               
    )
AS 
    DECLARE @re INT
    SET @re = -1
    BEGIN TRAN   
    UPDATE  [sysdata]
    SET     subvalue = @szValue1
    WHERE   subname = 'unitedisctax'  
		--由启用小数改到未启用小数
    IF @szValue11 = '0'
        AND EXISTS ( SELECT *
                     FROM   Sysdata
                     WHERE  subname = 'IfDecimalQty'
                            AND SubValue = '1' ) 
        BEGIN
            SET @modifydig = 1
            IF EXISTS ( SELECT TOP 1
                                1
                        FROM    GoodsstockDetail )
                OR EXISTS ( SELECT TOP 1
                                    1
                            FROM    iniGoodsDetail )
                OR EXISTS ( SELECT TOP 1
                                    1
                            FROM    bakdly ) 
                BEGIN
                    SET @re = -2
                    GOTO Error00
                END
        END
		--数量由不启用小数改到启用小数
    IF @szValue11 = '1'
        AND EXISTS ( SELECT *
                     FROM   Sysdata
                     WHERE  subname = 'IfDecimalQty'
                            AND SubValue = '0' ) 
        BEGIN
            SET @modifydig = 2
        END

    IF @szValue12 = '0'
        AND EXISTS ( SELECT *
                     FROM   Sysdata
                     WHERE  subname = 'IfDecimalDiscount'
                            AND SubValue = '1' ) 
        BEGIN
            SET @modifydig = 3
            IF EXISTS ( SELECT TOP 1
                                1
                        FROM    GoodsstockDetail )
                OR EXISTS ( SELECT TOP 1
                                    1
                            FROM    iniGoodsDetail )
                OR EXISTS ( SELECT TOP 1
                                    1
                            FROM    bakdly )
                OR EXISTS ( SELECT TOP 1
                                    1
                            FROM    PtypePrice ) 
                BEGIN
                    SET @re = -3
                    GOTO Error00
                END
        END
		--折扣由不启用小数改到启用小数
    IF @szValue12 = '1'
        AND EXISTS ( SELECT *
                     FROM   Sysdata
                     WHERE  subname = 'IfDecimalDiscount'
                            AND SubValue = '0' ) 
        BEGIN
            SET @modifydig = 4
        END

    UPDATE  [sysdata]
    SET     subvalue = @szValue2
    WHERE   subname = 'usesamecostmode'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue3
    WHERE   subname = 'billrow'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue4
    WHERE   subname = 'autobakupdays'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue5
    WHERE   subname = 'DecimalQty'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue6
    WHERE   subname = 'DecimalPrice'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue7
    WHERE   subname = 'DecimalTotal'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue8
    WHERE   subname = 'DecimalTaxRate'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue9
    WHERE   subname = 'DecimalDiscount'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue10
    WHERE   subname = 'CanPrintScreen'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue11
    WHERE   subname = 'IfDecimalQty'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue12
    WHERE   subname = 'IfDecimalDiscount'  
    UPDATE  [sysdata]
    SET     subvalue = @szValue13
    WHERE   subname = 'posPayConfig' 
    UPDATE  [sysdata]
    SET     subvalue = @szValue14
    WHERE   subname = 'PtypeUniqueSet' 
    UPDATE  [sysdata]
    SET     subvalue = @szValue15
    WHERE   subname = 'JMSLimit'
    UPDATE  [sysdata]
    SET     subvalue = @szValue16
    WHERE   subname = 'NBPHLimit'
    UPDATE  [sysdata]
    SET     subvalue = @szValue17
    WHERE   subname = 'usepos'
    UPDATE  [sysdata]
    SET     subvalue = @szValue18
    WHERE   subname = 'useUnique'
    UPDATE  [sysdata]
    SET     subvalue = @szValue19
    WHERE   subname = 'UniqueManageType'
    UPDATE  [sysdata]
    SET     subvalue = @szValue20
    WHERE   subname = 'tailBackPrice'
    UPDATE  [sysdata]
    SET     subvalue = @szValue21
    WHERE   subname = 'goodsInputStyle'
    UPDATE  [sysdata]
    SET     subvalue = @szValue22
    WHERE   subname = 'PHSQLimit'
    UPDATE  [sysdata] 
    SET     subvalue = @szValue23
    WHERE   subname = 'BoolDZT'
    --OA消息间隔
    UPDATE  [sysdata] 
    SET     subvalue = @szValue24
    WHERE   subname = 'OaMessageTime'
    --指定用户数
    UPDATE  [sysdata] 
    SET     subvalue = @szValue25
    WHERE   subname = 'UserNumber'
    
    --是否启用订货会
    UPDATE  [sysdata] 
    SET     subvalue = @szValue27
    WHERE   subname = 'mposetting'
    
    --产品名称
    UPDATE  [sysdata] 
    SET     subvalue = @szValue26
    WHERE   subname = 'CPName'
    
    --是否启用IC卡设备
    UPDATE  [sysdata] 
    SET     subvalue = @szValue28
    WHERE   subname = 'IsVipICCard'
    
    --IC卡设备会员卡标识
    UPDATE  [sysdata] 
    SET     subvalue = @szValue29
    WHERE   subname = 'ICCardMark'
    
    --IC卡设备名称
    UPDATE  [sysdata] 
    SET     subvalue = @szValue30
    WHERE   subname = 'VipICMachine'
    
		--改变系统小数位配置
    IF @szValue11 = '1' 
        UPDATE  numberconfig
        SET     digits = 2
        WHERE   typename = 'qty'
    ELSE 
        UPDATE  numberconfig
        SET     digits = 0
        WHERE   typename = 'qty'

    IF @szValue12 = '1' 
        UPDATE  numberconfig
        SET     digits = 2
        WHERE   typename = 'discount'
    ELSE 
        UPDATE  numberconfig
        SET     digits = 0
        WHERE   typename = 'discount'


    IF @@Error <> 0 
        GOTO Error00  
         
    GOTO Success00  
    Success00:  
    COMMIT TRAN   
    RETURN 0  
    Error00:  
    ROLLBACK TRAN   
    RETURN @re



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
---FN_FZGetBtypeBalance速度优化
IF NOT exists (select 1
        from  sysindexes
       where  id    = object_id('dbo.GatheringDly')
        and   name  = 'ix_index_Gatheringdly_VD'
        and   indid > 0
        and   indid < 255)
BEGIN
	CREATE NONCLUSTERED INDEX ix_index_Gatheringdly_VD
	ON [dbo].[GatheringDly] ([VchCode],[Draft])
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_FZGetBtypeBalance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FN_FZGetBtypeBalance]
GO




--在按单结算中单位的按单结算信息
--  ********************************************************************************************
--  ||                                                                                        
--  ||   过程名称：F_D_GetBtypeBalance                                     
--  ||   过程功能：按单结算
--  ||=========================================================================================
--  ||   参数说明：  参数名称         类型            意义                     输入输出
--  ||            -----------------------------------------------------------------------------
--  ||                       @BTypeID VARCHAR(50),  往来单位id
--  ||            	  @StartDate VARCHAR(10), 开始日期
--  ||          	  @EndDate VARCHAR(10), 结束日期
--  ||                       @VchType INT,                   VchType = 4  -- 收款单，66--付款单, 253--往来核销单
--  ||                       @CurBillNumerID int    当前单据的单据号
--  ||=========================================================================================   
--  ||   返回值：         值                                     说明
--  ||       ----------------------------------------------------------------------------------------
--  ||                    0                                 执行成功
--  ||                  －1                               执行失败
--  ||==========================================================================================
CREATE       PROCEDURE FN_FZGetBtypeBalance
(
	@BranchId	varchar(50),
	@BtypeId        varchar(50),
  	@StartDate      VARCHAR(10),--格式2012-06-05
	@EndDate        VARCHAR(10),--格式2012-06-05
	@VchType        int,
	@BanlanceVchType int,
        @CurBillNumerID bigint= 0,
        @ShopID         varchar(50) = ''
)
AS
  	SET NOCOUNT ON
	Select @BTypeID = LTRIM(RTRIM(@BTypeID)), @StartDate = LTRIM(RTRIM(@StartDate)), @EndDate = LTRIM(RTRIM(@EndDate))
	Select @ShopID = isnull(@ShopID,'') + '%' 
	
	declare @dt_startDate varchar(10),@dt_endDate varchar(10)
	
	if @StartDate<>'' and @EndDate<>''
		select @dt_startDate=@StartDate,@dt_endDate=@EndDate
	else 
		select @dt_startDate='1900-01-01',@dt_endDate='2100-01-01'
	
	---------------------------
	
	IF OBJECT_ID('tempdb..#BillData')IS NOT NULL DROP TABLE #BillData
	SELECT	d.bFullName ,
		d.btypeid ,
		d.VchName ,
		d.summary ,
		d.VchType ,
		d.Vchcode ,
		d.DlyVchcode ,
		d.[Date] ,
		d.Number ,
		d.Total AS VchTotal ,
		SUM(ISNULL(ABS(g.GatheringTotal), 0)) AS GatheringTotal ,
		d.Total
		- CASE WHEN d.total > 0
					AND d.vchtype NOT IN ( 12, 24 )
			   THEN SUM(ISNULL(ABS(g.GatheringTotal), 0))
			   WHEN d.total = 0
					AND d.vchtype = 34
			   THEN SUM(ISNULL(( -g.GatheringTotal ), 0))
			   WHEN d.vchtype = 24
					AND d.total < 0
			   THEN CASE WHEN SUM(ISNULL(-g.GatheringTotal, 0)) > 0
						 THEN -ABS(SUM(ISNULL(-g.GatheringTotal, 0)))
						 ELSE ABS(SUM(ISNULL(-g.GatheringTotal, 0)))
					END    --修改为先求绝对值，再加负号，对应Mantis问题编号0026940   
			   WHEN d.vchtype = 12 THEN SUM(ISNULL(( g.GatheringTotal ), 0))
			   WHEN d.vchtype = 253
					AND d.total < 0 THEN SUM(ISNULL(( -g.GatheringTotal ), 0))
			   ELSE SUM(ISNULL(g.GatheringTotal, 0))
		  END AS BalanceTotal ,       
		d.etypeid ,
		d.curktypeid AS ktypeid ,
		d.curbranchid AS branchid ,
		d.account INTO #BillData 
	 FROM	( SELECT	d.* ,
						CASE WHEN d.vchtype IN ( 222, 234 ) THEN d.branchid2
							 WHEN d.branchid3 <> '' THEN d.branchid3
							 ELSE d.branchid
						END AS curbranchid ,
						CASE WHEN d.vchtype IN ( 222, 234 ) THEN d.ktypeid2
							 ELSE d.ktypeid
						END AS curktypeid
			  FROM		dbo.view_zz_Dlyndx d
			) d
			LEFT OUTER JOIN ( SELECT	
										g.VchCode ,
										CASE WHEN d.vchtype = 24
												  AND g.[type] = 2 THEN -g.Total
											 ELSE g.Total
										END GatheringTotal 
							  FROM		dbo.DlyNdx d
										  INNER JOIN GatheringDly g ON d.VchCode = g.GatheringVchCode
							  WHERE		d.RedOld = 'F'
										AND g.draft = 2
							) g ON d.Vchcode = g.VchCode
	 WHERE	( d.VchType IN ( 11, 12, 13, 34, 6, 300, 301, 45, 26, 28, 24, 222, 224,
							 232, 234, 250 ) )
			AND ( d.draft = 2 )
			AND ( d.redold = 'F' )
			AND d.branchid =@BranchId 
		    And d.BTypeID = @BTypeID 
		    AND d.[date] between @dt_startDate and @dt_endDate 
	 GROUP BY d.bFullName ,
			d.btypeid ,
			d.VchName ,
			d.summary ,
			d.curktypeid ,
			d.VchType ,
			d.Vchcode ,
			d.DlyVchcode ,
			d.[Date] ,
			d.Number ,
			d.Total ,
			d.etypeid ,
			d.curbranchid ,
			d.account         
     
	---------------------------	
		

	If @VchType = 4  -- 收款单
	Begin
		Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number,
			 CASE WHEN b.vchtype IN (24,12,253) THEN VchTotal ELSE abs(VchTotal) END as VchTotal, GatheringTotal, 
			 CASE WHEN b.vchtype IN (24,12,253) THEN BalanceTotal ELSE abs(BalanceTotal) END as BalanceTotal, ETypeID,
			 (SELECT CASE WHEN  b.vchtype IN (24,12,253) THEN Sum(total) ELSE Sum(abs(total))  END 
			 from gatheringdly a where a.vchcode= b.vchcode and a.gatheringvchcode = @CurBillNumerID and draft = 2) Curbalance --当前结算单结算的金额
		From #billdata b
		Where  (((b.ktypeid in (Select typeid from stock where branchid like @ShopID+'%') 
        		And (b.vchtype IN (11,26,222,234) 
        		or b.vchtype in (24,12))  OR (b.VchType=253 AND EXISTS(SELECT 1 FROM dbo.DlyNdx WHERE b.Vchcode=Vchcode AND PHID=10    )) )
        			--应收冲应收 转入单位可能产生应付（负金额）
			And (case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end > 0
			 or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2))
       			And b.vchcode not in (select draftBillcode from Posretailbill))) 
		
       	UNION
       	Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number, -abs(VchTotal) as VchTotal, GatheringTotal, -abs(BalanceTotal) as BalanceTotal, ETypeID,
			(select -Sum(abs(total)) from gatheringdly a where a.vchcode= b.vchcode 
			and a.gatheringvchcode = @CurBillNumerID and draft = 2) Curbalance --当前结算单结算的金额
		From #billdata b
		Where  ((b.ktypeid in (Select typeid from stock where branchid like @ShopID+'%') 
        	And b.vchtype in (45,224)
			And (case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end > 0
			 or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2))
       			And b.vchcode not in (select draftBillcode from Posretailbill))) 
			
		Union
		--无收款单或有收款单为草稿，取期初
		Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
		From (
			Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应收款' as Summary, 
				-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
				'QCYS' as Number, isnull(bb.ARTotal00,0) as VchTotal,0 as GatheringTotal,
	    			(isnull(bb.ARTotal00,0) - isnull((
					Select sum(isnull(Total,0)) From GatheringDly 
					Where Btypeid = @BTypeID and vchCode = -1 and Type IN (1,3,5) and draft<>1 
						--And GatheringVchCode In (Select VchCode From DlyNdx where VchType IN (4,253) and redold = 'F')
						and exists(select 1 from dlyndx n where (n.vchtype=4 or n.vchtype=253) 
						and redold='F' and n.branchid=@BranchId and n.vchcode=GatheringVchCode)
					),0)) as balancetotal,
				'00000' as ETypeID,0 as Curbalance 
			From btype b,BranchBtype bb 
			Where b.typeid = @Btypeid And b.typeid=bb.btypeid and bb.branchid=@BranchId 
			) t	
		Where balancetotal <> 0 and (@CurBillNumerID=0 Or 
			Exists(Select 1 From DlyNdx Where VchCode=@CurBillNumerID And VchType IN (4,253) And Draft=1))
		Union
		--有收款单号且已过帐收款单，取期初
		Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
		From (
			Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应收款' as Summary, 
				-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) 
				From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
				'QCYS' as Number, isnull(bb.ARTotal00,0) as VchTotal,0 as GatheringTotal,
	    			(isnull(bb.ARTotal00,0) - isnull((
					Select sum(isnull(Total,0)) From GatheringDly 
					Where Btypeid = @BTypeID and vchCode = -1 and Type IN (1,3,5) and draft<>1 
						and exists(select 1 from dlyndx n where (n.vchtype=4 or n.vchtype=253)
						 and redold='F' and n.branchid=@BranchId and n.vchcode<>@CurBillNumerID and n.vchcode=GatheringVchCode)
					),0)) as balancetotal,
				'00000' as ETypeID,0 as Curbalance 
			From GatheringDly g,btype b ,BranchBtype bb
			Where gatheringvchcode = @CurBillNumerID And vchcode=-1 and b.typeid=g.btypeid 
				And b.typeid=bb.btypeid and bb.branchid=@BranchId
				And Exists(Select 1 From DlyNdx Where VchCode=@CurBillNumerID And VchType IN (4,253) And Draft=2)
			) t1
		
     		ORDER BY b.VchCode
	End
	ELSE IF @VchType = 66
	Begin
    		Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number, 
			case when b.VchType=253 then VchTotal else abs(VchTotal) end as VchTotal, GatheringTotal, 
			case when b.VchType=253 then BalanceTotal else abs(BalanceTotal) end as BalanceTotal, ETypeID,
			(Select case when b.VchType=253 then sum(total) else Sum(abs(total)) end 
			from gatheringdly a where a.vchcode= b.vchcode and a.gatheringvchcode = @CurBillNumerID) Curbalance
		FROM #billdata b
		Where ((
		     	((b.vchtype in (28,34,13,232) --(28,34,45,13,224,232)
				) OR (b.VchType=253 AND EXISTS(SELECT 1 FROM dbo.DlyNdx WHERE b.Vchcode=Vchcode AND PHID=11   )))
				--应付冲应付 转入单位可能产生应收（负金额）
			and (case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end  > 0 
			or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2)))) 
			
		UNION
			Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number, -abs(VchTotal) as VchTotal, GatheringTotal, -abs(BalanceTotal) as BalanceTotal, ETypeID,
			(Select -Sum(abs(total)) from gatheringdly a where a.vchcode= b.vchcode and a.gatheringvchcode = @CurBillNumerID) Curbalance
		FROM #billdata b
		Where ((b.vchtype in (6,234) 
			and (case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end  > 0 
			or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2))))
		
		Union
		--无付款单或有付款单为草稿，取期初
		Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
		From (
			Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应付款' as Summary, 
				-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
				'QCYF' as Number,isnull(bb.APTotal00,0) as VchTotal,0 as GatheringTotal,
				(isnull(bb.APTotal00,0) - isnull((
					Select sum(isnull( Total,0)) From GatheringDly 
					where Btypeid = @BTypeID and vchCode = -1 and Type IN (2,4,6) and  draft<>1 
						and exists(select 1 from dlyndx n where (n.vchtype=66 or n.vchtype=253) 
						and redold='F' and n.branchid=@BranchId and n.vchcode=GatheringVchCode)
					),0)) as balancetotal,
				'00000' as ETypeID,0 as Curbalance 
			From btype b,BranchBtype bb 
			Where b.typeid = @Btypeid And b.typeid=bb.btypeid and bb.branchid=@BranchId 
			) t
		Where balancetotal <> 0 And (@CurBillNumerID=0 
		Or Exists(Select 1 From DlyNdx Where VchCode=@CurBillNumerID And VchType IN (66,253) And Draft=1))
		Union
		--有付款单号且已过帐付款单，取期初
		Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
		From (
			Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应付款' as Summary, 
				-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
				'QCYF' as Number,isnull(bb.APTotal00,0) as VchTotal,0 as GatheringTotal,
				(isnull(bb.APTotal00,0) - isnull((
					Select sum(isnull(- Total,0)) From GatheringDly 
					where Btypeid = @BTypeID and vchCode = -1 and Type IN (2,4,6) and  draft<>1 
						--And GatheringVchCode In (Select VchCode From DlyNdx where VchType IN (66,253) and redold = 'F' And VchCode<>@CurBillNumerID)
						and exists(select 1 from dlyndx n where (n.vchtype=66 or n.vchtype=253) 
						and redold='F' and n.branchid=@BranchId And n.VchCode<>@CurBillNumerID and n.vchcode=GatheringVchCode)
					),0)) as balancetotal,
				'00000' as ETypeID,0 as Curbalance 
			From GatheringDly g, btype b,BranchBtype bb 
			Where gatheringvchcode = @CurBillNumerID And vchcode=-1 and b.typeid=g.btypeid And b.typeid=bb.btypeid and bb.branchid=@BranchId 
				And Exists(Select 1 From DlyNdx Where VchCode=@CurBillNumerID And VchType IN (66,253) And Draft=2)
			) t1
		Order by b.VchCode
	End
	else if @vchtype=253
	begin
		If @BanlanceVchType = 4  -- 收款单
		Begin
			Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number,
				 CASE WHEN b.vchtype IN (24,12,253) THEN VchTotal ELSE abs(VchTotal) END as VchTotal, GatheringTotal, 
				 CASE WHEN b.vchtype IN (24,12,253) THEN BalanceTotal ELSE abs(BalanceTotal) END as BalanceTotal, ETypeID,
				 (SELECT CASE WHEN  b.vchtype IN (24,12,253) THEN Sum(total) ELSE Sum(abs(total))  END 
				 from gatheringdly a where a.vchcode= b.vchcode 
				 and a.gatheringvchcode = @CurBillNumerID and draft = 2) Curbalance --当前结算单结算的金额
			From #billdata b
			Where (((b.ktypeid in (Select typeid from stock where branchid like @ShopID+'%') 
        			And (b.vchtype IN (11,26,234) 
					or (b.vchtype = 222 and exists (select 1 from dlyndx where vchcode=b.DlyVchcode and draft=2 ))--加盟商配货单需要验收
        			or b.vchtype in (24,12))  OR (b.VchType=253 AND EXISTS(SELECT 1 FROM dbo.DlyNdx WHERE b.Vchcode=Vchcode AND PHID=10  )) )
        			--应收冲应收 转入单位可能产生应付（负金额）
				And (case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end > 0 
				or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2))
       				And b.vchcode not in (select draftBillcode from Posretailbill))) 
			
       		UNION
       		Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number, -abs(VchTotal) as VchTotal, GatheringTotal, -abs(BalanceTotal) as BalanceTotal, ETypeID,
				(select -Sum(abs(total)) from gatheringdly a where a.vchcode= b.vchcode 
				     and a.gatheringvchcode = @CurBillNumerID and draft = 2) Curbalance --当前结算单结算的金额
			From #billdata b
			Where ((b.ktypeid in (Select typeid from stock where branchid like @ShopID+'%') 
        		And b.vchtype in (45,224)
				And (case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end > 0
				 or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2))
       				And b.vchcode not in (select draftBillcode from Posretailbill))) 
			Union
			--无收款单或有收款单为草稿，取期初
			Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
			From (
				Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应收款' as Summary, 
					-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
					'QCYS' as Number, isnull(bb.ARTotal00,0) as VchTotal,0 as GatheringTotal,
	    				(isnull(bb.ARTotal00,0) - isnull((
						Select sum(isnull(Total,0)) From GatheringDly 
						Where Btypeid = @BTypeID and vchCode = -1 and Type IN (1,3,5) and draft<>1 
							--And GatheringVchCode In (Select VchCode From DlyNdx where VchType IN (4,253) and redold = 'F')
							and exists(select 1 from dlyndx n where (n.vchtype=4 or n.vchtype=253) 
							and redold='F' and n.branchid=@BranchId and n.vchcode=GatheringVchCode)
						),0)) as balancetotal,
					'00000' as ETypeID,0 as Curbalance 
				From btype b,BranchBtype bb 
				Where b.typeid = @Btypeid And b.typeid=bb.btypeid and bb.branchid=@BranchId 
				) t	
			Where balancetotal <> 0 and (@CurBillNumerID=0 
			Or Exists(Select 1 From DlyNdx Where VchCode=@CurBillNumerID And VchType IN (4,253) And Draft=1))
			Union
			--有收款单号且已过帐收款单，取期初
			Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
			From (
				Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应收款' as Summary, 
					-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
					'QCYS' as Number, isnull(bb.ARTotal00,0) as VchTotal,0 as GatheringTotal,
	    				(isnull(bb.ARTotal00,0) - isnull((
						Select sum(isnull(Total,0)) From GatheringDly 
						Where Btypeid = @BTypeID and vchCode = -1 and Type IN (1,3,5) and draft<>1 
							and exists(select 1 from dlyndx n where (n.vchtype=4 or n.vchtype=253) 
							and redold='F' and n.branchid=@BranchId  And n.VchCode<>@CurBillNumerID and n.vchcode=GatheringVchCode)
						),0)) as balancetotal,
					'00000' as ETypeID,0 as Curbalance 
				From GatheringDly g,btype b ,BranchBtype bb
				Where gatheringvchcode = @CurBillNumerID And vchcode=-1 and b.typeid=g.btypeid And b.typeid=bb.btypeid and bb.branchid=@BranchId
					And Exists(Select 1 From DlyNdx Where VchCode=@CurBillNumerID And VchType IN (4,253) And Draft=2)
				) t1
			
     			ORDER BY b.VchCode
		End
		ELSE IF @BanlanceVchType = 66
		Begin
    			Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number, 
				case when b.VchType=253 then VchTotal else abs(VchTotal) end as VchTotal, GatheringTotal, 
				case when b.VchType=253 then BalanceTotal else abs(BalanceTotal) end as BalanceTotal, ETypeID,
				(Select case when b.VchType=253 then sum(total) else Sum(abs(total)) end 
				from gatheringdly a where a.vchcode= b.vchcode and a.gatheringvchcode = @CurBillNumerID) Curbalance
			FROM #billdata b
			Where (
			    	(
		     		(
					(b.vchtype in (28,34,13))
					OR (b.vchtype=232 and exists(select 1 from dlyndx where  b.Vchcode=Vchcode and draft=2))
					OR (b.VchType=253 AND EXISTS(SELECT 1 FROM dbo.DlyNdx WHERE b.Vchcode=Vchcode AND PHID=11   ))
					)--应付冲应付 转入单位可能产生应收（负金额）
					and 
					(case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end  > 0
					 or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2))
				)
				) 
	
			UNION
				Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number, -abs(VchTotal) as VchTotal, GatheringTotal, -abs(BalanceTotal) as BalanceTotal, ETypeID,
				(Select -Sum(abs(total)) from gatheringdly a where a.vchcode= b.vchcode and a.gatheringvchcode = @CurBillNumerID) Curbalance
			FROM #billdata b
			Where  ((b.vchtype in (6,234) 
				and (case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end  > 0 
				or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2))))
		
			Union
			--无付款单或有付款单为草稿，取期初
			Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
			From (
				Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应付款' as Summary, 
					-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
					'QCYF' as Number,isnull(bb.APTotal00,0) as VchTotal,0 as GatheringTotal,
					(isnull(bb.APTotal00,0) - isnull((
						Select sum(isnull(Total,0)) From GatheringDly 
						where Btypeid = @BTypeID and vchCode = -1 and Type IN (2,4,6) and  draft<>1 
							--And GatheringVchCode In (Select VchCode From DlyNdx where VchType IN (66,253) and redold = 'F')
							and exists(select 1 from dlyndx n where (n.vchtype=66 or n.vchtype=253) 
							and redold='F' and n.branchid=@BranchId and n.vchcode=GatheringVchCode)
						),0)) as balancetotal,
					'00000' as ETypeID,0 as Curbalance 
				From btype b,BranchBtype bb 
				Where b.typeid = @Btypeid And b.typeid=bb.btypeid and bb.branchid=@BranchId 
				) t
			Where balancetotal <> 0 And (@CurBillNumerID=0 
			  Or Exists(Select 1 From DlyNdx	Where VchCode=@CurBillNumerID And VchType IN (66,253) And Draft=1))
			Union
			--有付款单号且已过帐付款单，取期初
			Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
			From (
				Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应付款' as Summary, 
					-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
					'QCYF' as Number,isnull(bb.APTotal00,0) as VchTotal,0 as GatheringTotal,
					(isnull(bb.APTotal00,0) - isnull((
						Select sum(isnull(- Total,0)) From GatheringDly 
						where Btypeid = @BTypeID and vchCode = -1 and Type IN (2,4,6) and  draft<>1 
							and exists(select 1 from dlyndx n where (n.vchtype=4 or n.vchtype=253) and redold='F' 
							and n.branchid=@BranchId  And n.VchCode<>@CurBillNumerID and n.vchcode=GatheringVchCode)
						),0)) as balancetotal,
					'00000' as ETypeID,0 as Curbalance 
				From GatheringDly g, btype b,BranchBtype bb 
				Where gatheringvchcode = @CurBillNumerID And vchcode=-1 and b.typeid=g.btypeid And b.typeid=bb.btypeid and bb.branchid=@BranchId 
					And Exists(Select 1 From DlyNdx Where VchCode=@CurBillNumerID And VchType IN (66,253) And Draft=2)
				) t1
			Order by b.VchCode
		End
	end
	Else If @VchType = 0
		Select b.*, (Select Sum(total) From gatheringdly a Where a.vchcode= b.vchcode and a.gatheringvchcode = @CurBillNumerID) Curbalance
		From #billdata b
		Where  (b.BalanceTotal <> 0 or b.VchCode in (select vchcode 
			from GatheringDly where gatheringvchcode = @CurBillNumerID and draft=2))
		   
		Order By b.VchCode
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/******************************************20130708********************************************/
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZSaleYMD]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZSaleYMD]
GO




CREATE PROCEDURE FZSaleYMD
    (
      @szPtypeId VARCHAR(50),
      @szKtypeid VARCHAR(50),
      @szBtypeid VARCHAR(50),
      @BeginDate VARCHAR(10),
      @EndDate VARCHAR(10),
      @type VARCHAR(1),
      @ifstop VARCHAR(2),
      @attrib1 INT = -1,
      @attrib2 INT = -1,
      @attrib3 INT = -1,
      @attrib4 INT = -1,
      @Assist1TypeID INT = -1,
      @Assist2TypeID INT = -1,
      @Assist3TypeID INT = -1,
      @Assist4TypeID INT = -1,
      @SaleTraitname VARCHAR(1000),
      @Etypeid VARCHAR(50),
      @deptid VARCHAR(50),
      @branchid VARCHAR(50),
      @OperatorId VARCHAR(50)
    )
AS /*
alter by hww 2011年9月13日16:47:35
CS中，能够通过辅助属性进行过滤
*/  

    declare @btypeidlist varchar(30)
    if EXISTS(SELECT SubValue FROM sysdata WHERE SubName = 'ProcTypeName' AND Subvalue='FZCS') 
     set @btypeidlist = '1,2,3,4,6,7'
    else
      set @btypeidlist = '2,3,4,6'

    DECLARE @OperatorIsJM BIT
    SELECT  @OperatorIsJM = SelfHelp
    FROM    Branch a
            LEFT JOIN Employee b ON a.branchid = b.branchid
    WHERE   b.typeid = @OperatorId
  
    IF @SaleTraitName = '全部' 
        SET @SaleTraitName = ''   
    IF @branchid IS NULL 
        SET @branchid = ''  
    IF @szPtypeId IS NULL
        OR @szPtypeId = '' 
        SELECT  @szPtypeId = '%'  

--总部和加盟商共用一个，当不进行筛选单据的情况下，要把单据范围补齐  
    DECLARE @vchtype VARCHAR(100)
    IF LEFT(@branchid, 5) = '00001'
        OR @branchid = '' 
        BEGIN   
            SET @vchtype = '100,11,45,24,12,222,224,4,66' --总部统计的销售主体单据  
        END  
    ELSE 
        BEGIN   
            SET @vchtype = '11,12,45,24,4,66'   --加盟商统计的销售主体单据  
        END  

    SELECT  p1.[typeid]
    INTO    #temp_p
    FROM    FN_GetPowerRangePList(@OperatorId, @szPtypeId) p1 --ptype p1  
            LEFT JOIN ( SELECT  a.ptypeid,
                                a.attributeid,
                                b.typeid
                        FROM    ptypeattribute a,
                                assistattribute b
                        WHERE   a.attributeid = b.attributeid
                                AND typeid = @Assist1TypeID
                      ) ls1 ON @attrib1 <> -1
                               AND ls1.ptypeid = p1.typeid
            LEFT JOIN ( SELECT  a.ptypeid,
                                a.attributeid,
                                b.typeid
                        FROM    ptypeattribute a,
                                assistattribute b
                        WHERE   a.attributeid = b.attributeid
                                AND typeid = @Assist2TypeID
                      ) ls2 ON @attrib2 <> -1
                               AND ls2.ptypeid = p1.typeid
            LEFT JOIN ( SELECT  a.ptypeid,
                                a.attributeid,
                                b.typeid
                        FROM    ptypeattribute a,
                                assistattribute b
                        WHERE   a.attributeid = b.attributeid
                                AND typeid = @Assist3TypeID
                      ) ls3 ON @attrib3 <> -1
                               AND ls3.ptypeid = p1.typeid
            LEFT JOIN ( SELECT  a.ptypeid,
                                a.attributeid,
                                b.typeid
                        FROM    ptypeattribute a,
                                assistattribute b
                        WHERE   a.attributeid = b.attributeid
                                AND typeid = @Assist4TypeID
                      ) ls4 ON @attrib4 <> -1
                               AND ls4.ptypeid = p1.typeid
    WHERE   deleted = 0
            AND stop = CASE @ifstop
                         WHEN '0' THEN '0'
                         ELSE stop
                       END
            AND ( ( parid LIKE @szPtypeId + '%'
                    AND sonnum = 0
                  )
                  OR ( p1.typeid = @szPtypeid
                       AND sonnum = 0
                     )
                )
            AND ISNULL(ls1.attributeid, -1) = CASE WHEN @attrib1 = -1
                                                   THEN ISNULL(ls1.attributeid, -1)
                                                   ELSE @attrib1
                                              END
            AND ISNULL(ls2.attributeid, -1) = CASE WHEN @attrib2 = -1
                                                   THEN ISNULL(ls2.attributeid, -1)
                                                   ELSE @attrib2
                                              END
            AND ISNULL(ls3.attributeid, -1) = CASE WHEN @attrib3 = -1
                                                   THEN ISNULL(ls3.attributeid, -1)
                                                   ELSE @attrib3
                                              END
            AND ISNULL(ls4.attributeid, -1) = CASE WHEN @attrib4 = -1
                                                   THEN ISNULL(ls4.attributeid, -1)
                                                   ELSE @attrib4
                                              END  
       SELECT TypeId INTO #SaleYMD_B FROM FN_GetPowerRangeBList(@OperatorId, @szBtypeid, '1,2,3,4,6,7') FilterB 
       UNION SELECT ''
       SELECT TypeId INTO #SaleYMD_B1 FROM FN_GetPowerRangeBList(@OperatorId, @szBtypeid, @btypeidlist) FilterB
       UNION SELECT ''
       SELECT TypeId INTO #SaleYMD_E FROM FN_GetPowerRangeEList(@OperatorId, @EtypeID) FilterE
       UNION SELECT ''
       SELECT KTypeId INTO #SaleYMD_K  FROM FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) FilterK
       UNION SELECT ''
       SELECT BranchId INTO #SaleYMD_BC FROM FN_GetPowerRangeBCList(@OperatorID,'') FilterBC 
			WHERE EXISTS ( SELECT 1 FROM   Branch bc WHERE  bc.BranchId = FilterBC.Branchid AND bc.selfHelp = @OperatorIsJM )
       SELECT BranchId INTO #SaleYMD_BC1 FROM FN_GetPowerRangeBCList(@OperatorID,@BranchId) FilterBC
			WHERE EXISTS ( SELECT 1 FROM   Branch bc WHERE  bc.BranchId = FilterBC.Branchid AND bc.selfHelp = @OperatorIsJM )
	  SELECT GetID into #SaleYMD_VCH FROM   FN_GetIdStrListTable(@vchtype) FilterVch
       
       CREATE CLUSTERED INDEX I_SaleYMD_B_typeid ON #SaleYMD_B(TypeId)
       CREATE CLUSTERED INDEX I_SaleYMD_B1_typeid ON #SaleYMD_B1(TypeId)
       CREATE CLUSTERED INDEX I_SaleYMD_E_typeid ON #SaleYMD_E(TypeId)
       CREATE CLUSTERED INDEX I_SaleYMD_K_typeid ON #SaleYMD_K(KTypeId)
       CREATE CLUSTERED INDEX I_SaleYMD_BC_typeid ON #SaleYMD_BC(BranchId)
       CREATE CLUSTERED INDEX I_SaleYMD_BC1_typeid ON #SaleYMD_BC1(BranchId)
       CREATE CLUSTERED INDEX I_SaleYMD_VCH_typeid ON #SaleYMD_VCH(GetID)
       
    IF @type = 'Y' --按年统计  
        BEGIN  
			SELECT  SUBSTRING([date], 1, 4) AS [date],
                                        SUM(ISNULL(-s.[qty], 0)) AS [Qty],
                                        SUM(ISNULL(-s.[BargainTotal], 0)) AS Total,
                                        SUM(ISNULL(-s.CostTotal, 0)) AS CostTotal,
                                        SUM(ISNULL(-s.[BargainTotal], 0))
                                        - SUM(ISNULL(-s.CostTotal, 0)) AS Profittotal INTO #SaleYMD_dd
                                FROM    Dlydata s 
										inner join #SaleYMD_B FilterB ON s.BtypeId = FilterB.TypeId
										INNER JOIN #SaleYMD_E FilterE ON s.EtypeId = FilterE.TypeId
										inner join #SaleYMD_K FilterK on s.ktypeId = Filterk.KtypeId
										inner join #SaleYMD_BC1 FilterBC on s.Branchid = FilterBC.branchid
										inner join #SaleYMD_VCH FilterVch ON s.VchType = FilterVch.GetID
                                WHERE   s.billtype = 2
                                        AND s.redold = 'F'
                                        AND usedtype = CASE WHEN vchtype IN ( 222, 224 )
                                                            THEN 1
                                                            ELSE usedtype
                                                       END
	                                --AND s.BranchId LIKE @BranchId + '%'
	                                /*AND EXISTS ( SELECT GetID
	                                             FROM   FN_GetIdStrListTable(@vchtype) FilterVch
	                                             WHERE  s.VchType = FilterVch.GetID )  --单据类型  
                                        
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B FilterB
	                                             WHERE  s.BtypeId = FilterB.TypeId 
	                                          )
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  s.EtypeId = FilterE.TypeId )
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_K FilterK
	                                             WHERE  s.ktypeId = Filterk.KtypeId )
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC FilterBC
	                                             WHERE  s.Branchid = FilterBC.branchid )*/
                                GROUP BY SUBSTRING([date], 1, 4)
            SELECT DISTINCT
                    c.[date],
                    ds.qty,
                    ds.TOtal,
                    ds.costTotal,
                    ds.profittotal,
                    ISNULL(da.arTotal, 0) - ISNULL(db.apTotal, 0) AS arTotal,
                    ISNULL(back.HKTotal, 0) AS BackTotal
            FROM    ( SELECT  DISTINCT  SUBSTRING([date], 1, 4) AS [date]
                      FROM      dlyndx
                      WHERE     draft = 2
                                AND redold = 'F'
--                                 AND EXISTS ( SELECT GetID
--                                              FROM   FN_GetIdStrListTable(@vchtype) FilterVch
--                                              WHERE  dlyndx.VchType = FilterVch.GetID )  --单据类型  		   		   
--                                 AND
--                                 ( EXISTS ( SELECT 1
--                                              FROM   FN_GetPowerRangeBList(@OperatorId, @szBtypeid, '1,2,3,4,6,7') FilterB
--                                              WHERE  dlyndx.BtypeId = FilterB.TypeId )
--                                              OR dlyndx.BtypeId=''  	
--                                 )
--                                 AND
--                                 ( EXISTS ( SELECT 1
--                                              FROM   FN_GetPowerRangeEList(@OperatorId, @EtypeID) FilterE
--                                              WHERE  dlyndx.EtypeId = FilterE.TypeId )
--                                              OR dlyndx.EtypeId=''  	
--                                 )
--                                 AND
--                                 ( EXISTS ( SELECT 1
--                                              FROM   FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) FilterK
--                                              WHERE  dlyndx.ktypeId = Filterk.KtypeId OR dlyndx.ktypeId2 = Filterk.KtypeId )
--                                              OR dlyndx.KtypeId=''  	--收款单 仓库为空
--                                 )
--                                 AND  EXISTS ( SELECT 1
--                                              FROM   FN_GetPowerRangeBCList(@OperatorID, @BranchId) FilterBC
--                                              WHERE  dlyndx.Branchid = FilterBC.branchid OR dlyndx.Branchid2 = FilterBC.branchid )
                                AND SUBSTRING([date], 1, 4) BETWEEN @BeginDate AND @EndDate
                    ) C
                    LEFT JOIN #SaleYMD_dd ds ON ds.date = c.date
                    LEFT JOIN ( SELECT  SUBSTRING([date], 1, 4) AS [date],
                                        SUM(a.Total) AS ArTotal
                                FROM    dlya a
										inner  join #SaleYMD_B1 FilterB ON a.BtypeId = FilterB.TypeId
										INNER  JOIN #SaleYMD_E FilterE ON a.EtypeId = FilterE.TypeId
										inner  join #SaleYMD_BC1 FilterBC on a.Branchid = FilterBC.branchid
                                WHERE   a.atypeid = '0000100005'
                                        AND redold = 'F'
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 ) 
	                                /*AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )*/
                                GROUP BY SUBSTRING([date], 1, 4)
                              ) da ON c.[date] = da.[date]
                    LEFT JOIN ( SELECT  SUBSTRING([date], 1, 4) AS [date],
                                        SUM(a.Total) AS ApTotal
                                FROM    dlya a
										inner  join #SaleYMD_B1 FilterB ON a.BtypeId = FilterB.TypeId
										INNER  JOIN #SaleYMD_E FilterE ON a.EtypeId = FilterE.TypeId
										inner  join #SaleYMD_BC1 FilterBC on a.Branchid = FilterBC.branchid
                                WHERE   a.atypeid = '0000200001'
                                        AND redold = 'F'
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 ) --单据类型
	                                /*AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )*/
                                GROUP BY SUBSTRING([date], 1, 4)
                              ) db ON c.[date] = db.[date]
                    LEFT JOIN ( SELECT  SUBSTRING([date], 1, 4) AS [date],
                                        SUM(CASE a.atypeid
                                              WHEN '0000299999' THEN -a.Total
                                              ELSE a.total
                                            END) AS HKTotal
                                FROM    dlya a
										inner  join #SaleYMD_B1 FilterB ON a.BtypeId = FilterB.TypeId
										INNER  JOIN #SaleYMD_E FilterE ON a.EtypeId = FilterE.TypeId
										inner  join #SaleYMD_BC1 FilterBC on a.Branchid = FilterBC.branchid
                                WHERE   ( LEFT(a.atypeid, 10) IN (
                                          '0000100003', '0000100004' )
                                          OR a.atypeid = '000040000300006'
                                          OR a.atypeid = '0000299999'
                                        )
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND redold = 'F'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 )--单据类型 
	                                /*AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )*/
                                GROUP BY SUBSTRING([date], 1, 4)
                              ) back ON c.[date] = back.[date]  
            RETURN 0
        END  
    IF @type = 'M' --按月统计  
        BEGIN  
            SELECT DISTINCT
                    c.[date],
                    ds.qty,
                    ds.TOtal,
                    ds.costTotal,
                    ds.profittotal,
                    ISNULL(da.arTotal, 0) - ISNULL(db.apTotal, 0) AS arTotal,
                    ISNULL(back.HKTotal, 0) AS BackTotal
            FROM    ( SELECT DISTINCT   SUBSTRING([date], 1, 7) AS [date]
                      FROM      dlyndx
                      WHERE     draft = 2
                                AND redold = 'F'
                                AND EXISTS ( SELECT GetID
                                             FROM   FN_GetIdStrListTable(@vchtype) FilterVch
                                             WHERE  dlyndx.VchType = FilterVch.GetID )  --单据类型  		   		   
                                AND
                                ( EXISTS ( SELECT 1
                                             FROM   #SaleYMD_B FilterB
                                             WHERE  dlyndx.BtypeId = FilterB.TypeId )
                                             OR dlyndx.BtypeId=''  	
                                )
                                AND
                                ( EXISTS ( SELECT 1
                                             FROM   #SaleYMD_E FilterE
                                             WHERE  dlyndx.EtypeId = FilterE.TypeId )
                                             OR dlyndx.EtypeId=''  	
                                )
                                AND
                                ( EXISTS ( SELECT 1
                                             FROM   #SaleYMD_K FilterK
                                             WHERE  dlyndx.ktypeId = Filterk.KtypeId OR dlyndx.ktypeId2 = Filterk.KtypeId )
                                             OR dlyndx.KtypeId=''  	--收款单 仓库为空
                                )
                                AND  EXISTS ( SELECT 1
                                             FROM   #SaleYMD_BC1 FilterBC
                                             WHERE  dlyndx.Branchid = FilterBC.branchid OR dlyndx.Branchid2 = FilterBC.branchid )
                                AND SUBSTRING([date], 1, 7) BETWEEN @BeginDate AND @EndDate
                    ) C
                    LEFT JOIN ( SELECT  SUBSTRING([date], 1, 7) AS [date],
                                        SUM(ISNULL(-s.[qty], 0)) AS [Qty],
                                        SUM(ISNULL(-s.[BargainTotal], 0)) AS Total,
                                        SUM(ISNULL(-s.CostTotal, 0)) AS CostTotal,
                                        SUM(ISNULL(-s.[BargainTotal], 0))
                                        - SUM(ISNULL(-s.CostTotal, 0)) AS Profittotal,
                                        SUM(CASE WHEN vchtype IN ( 100, 101 )
                                                 THEN -( BargainTotal )
                                                 ELSE 0
                                            END) AS zgccTotal
                                FROM    Dlydata S
                                WHERE   SUBSTRING([date], 1, 7) BETWEEN @BeginDate AND @EndDate
                                        AND usedtype = CASE WHEN vchtype IN ( 222, 224 )
                                                            THEN 1
                                                            ELSE usedtype
                                                       END
                                        AND s.billtype = 2
                                        AND s.redold = 'F'
	                                AND s.BranchId LIKE @BranchId + '%'
	                                AND EXISTS ( SELECT GetID
	                                             FROM   FN_GetIdStrListTable(@vchtype) FilterVch
	                                             WHERE  s.VchType = FilterVch.GetID )  --单据类型  
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B FilterB
	                                             WHERE  s.BtypeId = FilterB.TypeId )
	                                             OR s.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  s.EtypeId = FilterE.TypeId )
	                                             OR s.EtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_K FilterK
	                                             WHERE  s.ktypeId = Filterk.KtypeId )
	                                             OR s.KtypeId=''  	--收款单 仓库为空
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC FilterBC
	                                             WHERE  s.Branchid = FilterBC.branchid )
                                GROUP BY SUBSTRING([date], 1, 7)
                              ) ds ON ds.[date] = c.[date]
                    LEFT JOIN ( SELECT  SUBSTRING([date], 1, 7) AS [date],
                                        SUM(a.Total) AS ArTotal
                                FROM    dlya a
                                WHERE   a.atypeid = '0000100005'
                                        AND redold = 'F'
                                        AND SUBSTRING([date], 1, 7) BETWEEN @BeginDate AND @EndDate
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 ) --单据类型
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )
                                GROUP BY SUBSTRING([date], 1, 7)
                              ) da ON c.[date] = da.[date]
                    LEFT JOIN ( SELECT  SUBSTRING([date], 1, 7) AS [date],
                                        SUM(a.Total) AS ApTotal
                                FROM    dlya a
                                WHERE   a.atypeid = '0000200001'
                                        AND redold = 'F'
                                        AND SUBSTRING([date], 1, 7) BETWEEN @BeginDate AND @EndDate
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66) --单据类型 
                                     AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )
                                GROUP BY SUBSTRING([date], 1, 7)
                              ) db ON c.[date] = db.[date]
                    LEFT JOIN ( SELECT  SUBSTRING([date], 1, 7) AS [date],
                                        SUM(CASE a.atypeid
                                              WHEN '0000299999' THEN -a.Total
                                              ELSE a.total
                                            END) AS HKTotal
                                FROM    dlya a
                                WHERE   ( LEFT(a.atypeid, 10) IN (
                                          '0000100003', '0000100004' )
                                          OR a.atypeid = '000040000300006'
                                          OR a.atypeid = '0000299999'
                                        )
                                        AND SUBSTRING([date], 1, 7) BETWEEN @BeginDate AND @EndDate
                                        AND redold = 'F'
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 ) --单据类型  	
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )
                                GROUP BY SUBSTRING([date], 1, 7)
                              ) back ON c.[date] = back.[date]  
 
            RETURN 0
        END  
    IF @type = 'D' --按日统计  
        BEGIN  
            SELECT DISTINCT
                    c.[date],
                    ds.qty,
                    ds.TOtal,
                    ds.costTotal,
                    ds.profittotal,
                    ISNULL(da.arTotal, 0) - ISNULL(db.apTotal, 0) AS arTotal,
                    ISNULL(back.HKTotal, 0) AS BackTotal
            FROM    ( SELECT  DISTINCT  [date]
                      FROM      dlyndx
                      WHERE     draft = 2
                                AND redold = 'F'
                                AND EXISTS ( SELECT GetID
                                             FROM   FN_GetIdStrListTable(@vchtype) FilterVch
                                             WHERE  dlyndx.VchType = FilterVch.GetID )  --单据类型  		   		   
                                AND
                                ( EXISTS ( SELECT 1
                                             FROM   #SaleYMD_B FilterB
                                             WHERE  dlyndx.BtypeId = FilterB.TypeId )
                                             OR dlyndx.BtypeId=''  	
                                )
                                AND
                                ( EXISTS ( SELECT 1
                                             FROM   #SaleYMD_E FilterE
                                             WHERE  dlyndx.EtypeId = FilterE.TypeId )
                                             OR dlyndx.EtypeId=''  	
                                )
                                AND
                                ( EXISTS ( SELECT 1
                                             FROM   #SaleYMD_K FilterK
                                             WHERE  dlyndx.ktypeId = Filterk.KtypeId OR dlyndx.ktypeId2 = Filterk.KtypeId )
                                             OR dlyndx.KtypeId=''  	--收款单 仓库为空
                                )
                                AND  EXISTS ( SELECT 1
                                             FROM   #SaleYMD_BC1 FilterBC
                                             WHERE  dlyndx.Branchid = FilterBC.branchid OR dlyndx.Branchid2 = FilterBC.branchid )
                                AND [date] BETWEEN @BeginDate AND @EndDate
                    ) C
                    LEFT JOIN ( SELECT  [date],
                                        SUM(ISNULL(-ss.[qty], 0)) AS [Qty],
                                        SUM(ISNULL(-ss.[BargainTotal], 0)) AS Total,
                                        SUM(ISNULL(-ss.CostTotal, 0)) AS CostTotal,
                                        SUM(ISNULL(-ss.[BargainTotal], 0))
                                        - SUM(ISNULL(-ss.CostTotal, 0)) AS Profittotal,
                                        SUM(CASE WHEN vchtype IN ( 100, 101 )
                                                 THEN -( BargainTotal )
                                                 ELSE 0
                                            END) AS zgccTotal
                                FROM    Dlydata ss
                                WHERE   [date] BETWEEN @BeginDate AND @EndDate
                                        AND usedtype = CASE WHEN vchtype IN ( 222, 224 )
                                                            THEN 1
                                                            ELSE usedtype
                                                       END
                                        AND ss.billtype = 2
                                        AND ss.redold = 'F'
										AND ss.BranchId LIKE @BranchId + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 ) --单据类型	
	                                AND EXISTS ( SELECT GetID
	                                             FROM   FN_GetIdStrListTable(@vchtype) FilterVch
	                                             WHERE  ss.VchType = FilterVch.GetID )  --单据类型  
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B FilterB
	                                             WHERE  ss.BtypeId = FilterB.TypeId )
	                                             OR ss.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  ss.EtypeId = FilterE.TypeId )
	                                             OR ss.EtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_K FilterK
	                                             WHERE  ss.ktypeId = Filterk.KtypeId )
	                                             OR ss.KtypeId=''  	--收款单 仓库为空
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC FilterBC
	                                             WHERE  ss.Branchid = FilterBC.branchid )
                                GROUP BY [date]
                              ) ds ON ds.[date] = c.[date]
                    LEFT JOIN ( SELECT  [date],
                                        SUM(a.Total) AS ArTotal
                                FROM    dlya a
                                WHERE   a.atypeid = '0000100005'
                                        AND redold = 'F'
                                        AND [date] BETWEEN @BeginDate AND @EndDate
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 ) --单据类型   	
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )
                                GROUP BY [date]
                              ) da ON c.[date] = da.[date]
                    LEFT JOIN ( SELECT  [date],
                                        SUM(a.Total) AS ApTotal
                                FROM    dlya a
                                WHERE   a.atypeid = '0000200001'
                                        AND redold = 'F'
                                        AND [date] BETWEEN @BeginDate AND @EndDate
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 )   		   
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )
                                GROUP BY [date]
                              ) db ON c.[date] = db.[date]
                    LEFT JOIN ( SELECT  [date],
                                        SUM(CASE a.atypeid
                                              WHEN '0000299999' THEN -a.Total
                                              ELSE a.total
                                            END) AS HKTotal
                                FROM    dlya a
                                WHERE   ( LEFT(a.atypeid, 10) IN (
                                          '0000100003', '0000100004' )
                                          OR a.atypeid = '000040000300006'
                                          OR a.atypeid = '0000299999'
                                        )
                                        AND [date] BETWEEN @BeginDate AND @EndDate
                                        AND redold = 'F'
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 ) 		   
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )
                                GROUP BY [date]
                              ) back ON c.[date] = back.[date]  
 
            RETURN 0
        END
  


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/******************************************20130712********************************************/


--操作员多IP设置
IF NOT EXISTS ( SELECT  * FROM    dbo.sysobjects WHERE   id = OBJECT_ID(N'[dbo].[LoginIP]')AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
CREATE TABLE [dbo].LoginIP
(
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[EtypeID] [varchar](50) COLLATE Chinese_PRC_CI_AS,
	IpAddr varchar(50) not NULL default '' ,
	IpMax char(10)  not NULL  default ''
)
ON  [PRIMARY]
GO
if not exists(select * from LoginIP)
insert into LoginIP(etypeid,ipaddr,ipmax) select etypeid,isnull(ipaddr,'') as ipaddr,isnull(ipmax,'') as ipmax from LoginUser where IpMax is not null
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
if not exists(select 1 from syscon where [order]=252)
insert into syscon([order],[name],[stats],number)
values(252,'物流单据启用商品图片预览',1,1)
GO

--模块信息
IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[QueryModule]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
CREATE TABLE [dbo].[QueryModule]
(
[QueryModuleId] [int] NOT NULL,
[ModuleName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL,
[IsEmbeded] [bit] NOT NULL CONSTRAINT [DF__QueryModu__IsEmb__53AD53A4] DEFAULT ((0))
) ON [PRIMARY]
GO

--模块明细
IF NOT EXISTS ( SELECT  *
                FROM    dbo.sysobjects
                WHERE   id = OBJECT_ID(N'[dbo].[QueryField]')
                        AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) 
CREATE TABLE [dbo].[QueryField]
(
[QueryFieldId] [int] NOT NULL,
[QueryModuleId] [int] NOT NULL,
[TableName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__QueryFiel__Table__5689C04F] DEFAULT (''),
[TableViewName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__QueryFiel__Table__577DE488] DEFAULT (''),
[FieldName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__QueryFiel__Field__587208C1] DEFAULT (''),
[FieldViewName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__QueryFiel__Field__59662CFA] DEFAULT (''),
[OrderNo] [int] NOT NULL,
[DataType] [varchar] (20) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__QueryFiel__DataT__5A5A5133] DEFAULT (''),
[ControlType] [varchar] (100) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__QueryFiel__Contr__5B4E756C] DEFAULT (''),
[ControlParam] [varchar] (500) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__QueryFiel__Contr__5C4299A5] DEFAULT (''),
[IsPrimaryKey] [bit] NOT NULL CONSTRAINT [DF__QueryFiel__IsPri__5D36BDDE] DEFAULT ((0)),
[MultiValueMode] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__QueryFiel__Multi__5E2AE217] DEFAULT (''),
[Datalength] [int] NOT NULL CONSTRAINT [DF__QueryFiel__Datal__5F1F0650] DEFAULT ((0)),
[BaseData] [varchar] (2000) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__QueryFiel__BaseD__60132A89] DEFAULT (''),
[ValueRequired] [bit] NOT NULL CONSTRAINT [DF__QueryFiel__Value__61074EC2] DEFAULT ((0)),
[WhichPanel] [int] default (2)
) ON [PRIMARY]
GO


 --DELETE FROM dbo.QuerySchemaDetail
 --GO
 --DELETE FROM dbo.QuerySchema
 --GO

GO
DELETE FROM [QueryField]

GO
DELETE FROM [QueryModule]

GO


/*
	--模块信息表
*/

INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('1',	'采购订单明细分析',		'1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('2',	'采购订单汇总分析',		'1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('3',	'商店sku动销比分析',		'1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('4',	'商店商品售罄率分析',		'1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('5',	'商店零售分析',			'1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('6',	'商品零售综合分析',		'1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('7',	'采购汇总分析',			'1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('8',	'库存周转率分析',		'1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('9',	'零售时段分析',			'1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('10',	'商品售罄率分析',		'1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('11',	'销售状况表',			'1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('12',	'客户上货情况分析表',		'1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('13', '商品销售分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('14', '销售订单明细分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('15', '配货单汇总分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('16', '配货申请单明细分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('17', '销售收款统计',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('18', '销售订单汇总分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('19', '发货类型销售分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('20', '供应商供货准时分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('21', '零售对比分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('22', '价格变迁零售统计',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('23', '配货申请单汇总分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('24', '零售单汇总分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('25', '商品零售分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('26', '商品畅滞销分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('27', '供应商供货对照表',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('28', '零售单明细分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('29', '供应商供货统计',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('30', '销售明细分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('31', '销售综合分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('32', '促销赠品分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) VALUES ('33', '供应商供货准时分析',         '1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('34', '销售排行榜','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('35', '采购明细分析','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('36', '机构盈利统计分析','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('37', '机构采购分布汇总统计','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('38', '发货类型销售分析','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('39', '配货单明细分析','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('40', '采购建议表','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('41', '机构销售分布汇总统计','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('42', '商品进销存分析','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('43', '库龄分析','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('44', '销售成本分析','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('45', 'POS销存动态跟踪','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('46', '商品畅滞销分析','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('47', '机构促销分析','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('48', '商品零售分析','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('49', '赠品分析','1')
INSERT INTO [QueryModule](QueryModuleId,ModuleName,IsEmbeded) values ('50', '机构收款统计','1')	

--- ----------------------------------------------------------------------目前最大 QueryModuleId 是 50




/*
	--模块明细表  
	--备注:每张报表 预留30个QueryFieldId编号,ID超出部分以底部"目前超出QueryFieldID"-1  进行编号，
	--     并更改"目前超出QueryFieldID"
*/
 
 --1.采购订单明细分析
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 1,1,'branch','分支机构','ctypeid','机构名称',2,'int','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid;TypeName==rsCtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 2,1,'btype','往来单位','btypeid','供应商',3,'int','TC','Tag==SELECTTYPE=1|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsBtype;',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 3,1,'stock','仓库','ktypeid','仓库',4,'int','TC','Tag==SELECTTYPE=7|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 4,1,'employee','雇员','etypeid','经手人',5,'int','TC','Tag==SELECTTYPE=0|ISQUICKQUERY=1;TypeName==rsEtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 5,1,'operationinfo','交易信息','opid','收货类型',6,'int','CheckBoxList','',0,'',0,'类型1★◎♂1,类型2★◎♂2',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 6,1,'PriceType','售价类型','salepriceid','参考价格',7,'char','','',0,'',0,'必写1★◎♂0,必写2★◎♂1',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 7,1,'__NotUse__','录单开始日期','billdate_s','录单开始日期',8,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 8,1,'__NotUse__','录单截止日期','billdate_e','录单截止日期',9,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 9,1,'__NotUse__','交货开始日期','checktime_s','交货开始日期',10,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 10,1,'__NotUse__','交货截止日期','checktime_e','交货截止日期',11,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 11,1,'__NotUse__','审核状态','ifaudit','审核状态',13,'char','CheckBoxList','Height==60;',0,'',0,'全部审核★◎♂0,未审核★◎♂1,审核未通过★◎♂2',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 12,1,'definetype','自定义类型','definetype','自定义类型   ',14,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 13,1,'definename','类型名称','definename','类型名称',15,'int','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 14,1,'__NotUse__','包含停用商品','containsstop','包含停用商品',1,'bit','','',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 15,1,'__NotUse__','商品','ptypeid','商品全名',2,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsPtype',0,'',0,'',0,2) 
 --INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	--VALUES ( 16,1,'bakdlyorder','维度列','dlistfield','配置列',-1,'int','DragableCheckBoxList','Height==65;',0,'',0,'录单日期-date,单据编号-number,交货日期-todate,收货类型-opid,摘要-summary',0,3) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 17,1,'bakdlyorder','分布列明细','ddistdetailfield','显示字段',1,'int','CheckBoxList','Height==350;',0,'',0,'订货数量★◎♂dhqty,订货参考单价★◎♂dhrefprice,订货参考金额★◎♂dhreftotal,,订货折扣(%)★◎♂dhdiscount,订货含税单价★◎♂dhtaxprice,订货含税金额★◎♂dhtax_total,订货无税单价★◎♂dhprice,订货无税金额★◎♂dhtotal,订货税率★◎♂dhtax1,订货税额★◎♂dhtaxtotal,订货折扣额★◎♂dhdiscounttotal,到货数量★◎♂tpqty,到货含税金额★◎♂tptax_total,到货参考金额★◎♂tpreftotal,终止数量★◎♂endqty,终止含税金额★◎♂endtax_total,终止参考金额★◎♂endreftotal,未到货数量★◎♂notqty,未到货含税金额★◎♂nottax_total,未到货参考金额★◎♂notreftotal,到货率(%)★◎♂topercent,完成率(%)★◎♂endpercent',0,3)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 18,1,'__NotUse__','查询方式','querymethod','查询方式',-1,'char','','',0,'',0,'商品★◎♂ptypeid,经手人★◎♂etypeid,供应商★◎♂btypeid',1,1) 

 
 --2.采购订单汇总分析
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 31,2,'branch','分支机构','ctypeid','机构名称',2,'int','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid;TypeName==rsCtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 32,2,'stock','仓库','ktypeid','仓库',3,'int','TC','Tag==SELECTTYPE=7|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 33,2,'btype','往来单位','btypeid','供应商',4,'int','TC','Tag==SELECTTYPE=15|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsBtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 34,2,'employee','雇员','etypeid','经手人',5,'int','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1;TypeName==rsEtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 35,2,'operationinfo','交易信息','opid','收货类型',6,'int','CheckBoxList','',0,'',0,'类型1★◎♂1,类型2★◎♂2',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 36,2,'PriceType','售价类型','salepriceid','参考价格',7,'char','','',0,'',0,'参考价1★◎♂0,参考价2★◎♂1',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 37,2,'__NotUse__','录单开始日期','billdate_s','录单开始日期',8,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 38,2,'__NotUse__','录单截止日期','billdate_e','录单截止日期',9,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 39,2,'__NotUse__','交货开始日期','checktime_s','交货开始日期',10,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 40,2,'__NotUse__','交货截止日期','checktime_e','交货截止日期',11,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 41,2,'__NotUse__','审核状态','ifaudit','审核状态',12,'int','CheckBoxList','',0,'',0,'全部审核★◎♂0,未审核★◎♂1,审核未通过★◎♂2',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 42,2,'definetype','自定义类型','definetype','自定义类型	',13,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 43,2,'definename','类型名称','definename','类型名称',14,'int','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 44,2,'ptypecategory','商品类别','ptypecategory','商品类别',17,'int','CheckBoxList','Height==65;',0,'',0,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 45,2,'__NotUse__','商品','ptypeid','商品全名',16,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 46,2,'__NotUse__','包含停用商品','containsstop','包含停用商品',15,'bit','','',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 47,2,'bakdlyorder','维度列','dlistfield','配置列',18,'int','DragableCheckBoxList','Height==200;data_appendgoodstrait==true',0,'',0,'经手人★◎♂etypeid,供应商★◎♂btypeid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 48,2,'bakdlyorder','分布列明细','ddistdetailfield','显示字段',19,'int','CheckBoxList','Height==65;',0,'',0,'订货数量★◎♂dhqty,订货参考单价★◎♂dhrefprice,订货参考金额★◎♂dhreftotal,订货折扣率★◎♂dhdiscount1,订货无税单价★◎♂dhprice,订货含税单价★◎♂dhtaxprice,订货无税金额★◎♂dhtotal,订货税率★◎♂dhtax1,订货税额★◎♂dhtaxtotal,订货含税金额★◎♂dhtax_total,订货折扣额★◎♂dhdiscounttotal,到货数量★◎♂tpqty,到货含税金额★◎♂tptax_total,到货参考金额★◎♂tpreftotal,终止数量★◎♂endqty,终止含税金额★◎♂endtax_total,终止参考金额★◎♂endreftotal,未到货数量★◎♂notqty,未到货含税金额★◎♂nottax_total,未到货参考金额★◎♂notreftotal,到货率(%)★◎♂topercent,完成率(%)★◎♂endpercent',0,3) 

 --3.商店sku动销比分析
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 61,3,'branch','分支机构','branchid','机构名称',1,'nvarchar','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid;TypeName==rsCtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 69,3,'stock','仓库','ktypeid','仓库',2,'nvarchar','TC','Tag==PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 62,3,'__NotUse__','开始日期','billdate_s','开始日期      ',3,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 63,3,'__NotUse__','截止日期','billdate_e','截止日期      ',4,'date','','',0,'',0,'',1,1) 
 --INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
--	VALUES ( 64,3,'definetype','自定义类型','definetype','自定义类型	   ',5,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1) 
 --INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
--	VALUES ( 65,3,'definename','类型名称','definename','类型名称',6,'int','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 70,3,'__NotUse__','包含停用商品','containsstop','包含停用商品',7,'bit','','',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 66,3,'__NotUse__','商品','ptypeid','商品全名',8,'nvarchar','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 67,3,'__NotUse__','颜色','colorid','颜色',9,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 68,3,'__NotUse__','尺码','sizeid','尺码',10,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2) 


 --4.商店商品售罄率分析
--4.商店商品售罄率分析
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 95,4,'branch','机构','branchid','机构名称',1,'NVARCHAR','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=ktypeid;TypeName==rsCtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 104,4,'stock','仓库','ktypeid','仓库',2,'NVARCHAR','TC','Tag==SELECTTYPE=7|PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 91,4,'__NotUse__','开始日期','billdate_s','开始日期',3,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 92,4,'__NotUse__','截止日期','billdate_e','截止日期',4,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 93,4,'__NotUse__','上市开始日期','publishtime_s','上市开始日期',5,'date','','',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 94,4,'__NotUse__','上市结束日期','publishtime_e','上市结束日期',6,'date','','',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 96,4,'definetype','自定义类型','definetype','自定义类型	   ',7,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 97,4,'definename','类型名称','definename','类型名称',8,'NVARCHAR','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',60,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 105,4,'__NotUse__','包含停用商品','containsstop','包含停用商品',9,'bit','','',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 98,4,'__NotUse__','商品','ptypeid','商品全名',10,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 99,4,'ptypecategory','商品类别','ptypecategory','商品类别',11,'NVARCHAR','CheckBoxList','Height==65;',0,'',60,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 100,4,'__NotUse__','颜色','colorid','颜色',12,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 101,4,'__NotUse__','尺码','sizeid','尺码',13,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 102,4,'bakdlyorder','维度列','dlistfield','配置列',14,'NVARCHAR','DragableCheckBoxList','Height==200;data_appendgoodstrait==true',0,'',400,'商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 103,4,'bakdlyorder','分布列明细','ddistdetailfield','显示字段',15,'NVARCHAR','CheckBoxList','Height==65;',0,'',400,'采购入库★◎♂cgrkqty,配货入库★◎♂phrkqty,配货调配入库★◎♂dprkqty,配货退货入库★◎♂thrkqty,销售退货入库★◎♂xsthrkqty,加盟配货退货入库★◎♂jmthrkqty,入库合计★◎♂rktotalqty,销售出库★◎♂xsckqty,配货出库★◎♂phckqty,配货调配出库★◎♂dpckqty,配货退货出库★◎♂thckqty,加盟配货出库★◎♂jmphckqty,出库合计★◎♂cktotalqty,实际入库★◎♂sjrktotalqty,售罄率%★◎♂sqlpercent',0,3) 

--5.商店零售分析
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 121,5,'branch','分支机构','branchid','机构名称',1,'NVARCHAR','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=ktypeid,etypeid;TypeName==rsCtype',0,'',60,'',0,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 131,5,'stock','仓库','ktypeid','仓库',2,'NVARCHAR','TC','Tag==PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 132,5,'employee','雇员','etypeid','经手人',2,'NVARCHAR','TC','Tag==SELECTTYPE=0|ISQUICKQUERY=1|ISMUSTPARENT=1|PARENTCONTROL=branchid;TypeName==rsEtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 122,5,'__NotUse__','开始日期','billdate_s','开始日期',3,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 123,5,'__NotUse__','截止日期','billdate_e','截止日期',4,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 124,5,'definetype','自定义类型','definetype','自定义类型',5,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 125,5,'definename','类型名称','definename','类型名称',6,'NVARCHAR','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',60,'',0,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 126,5,'__NotUse__','商品','ptypeid','商品全名',8,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 127,5,'__NotUse__','颜色','pcrec','颜色',9,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 128,5,'__NotUse__','尺码','psrec','尺码',10,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2)  
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 129,5,'__NotUse__','包含停用商品','containsstop','包含停用商品',7,'bit','','',0,'',0,'',0,2) 
	
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 130,5,'__NotUse__','维度列','dlistfield','配置列',12,'NVARCHAR','DragableCheckBoxList','Height==45;',0,'',200,'机构★◎♂branchid,经手人★◎♂etypeid',1,3) 


--6.商品零售综合分析
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 151,6,'branch','分支机构','branchid','机构名称',1,'NVARCHAR','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=ktypeid;TypeName==rsCtype',0,'',60,'',0,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 163,6,'stock','仓库','ktypeid','仓库',2,'NVARCHAR','TC','Tag==PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',60,'',0,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 152,6,'__NotUse__','开始日期','billdate_s','开始日期',3,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 153,6,'__NotUse__','截止日期','billdate_e','截止日期',4,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 154,6,'definetype','自定义类型','definetype','自定义类型   ',5,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 155,6,'definename','类型名称','definename','类型名称',6,'NVARCHAR','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',60,'',0,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 156,6,'__NotUse__','商品全名','ptypeid','商品全名',8,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 157,6,'ptypecategory','商品类别','ptypecategory','商品类别',9,'NVARCHAR','CheckBoxList','Height==65;',0,'',50,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 158,6,'__NotUse__','颜色','pcrec','颜色',10,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 159,6,'__NotUse__','尺码','psrec','尺码',11,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 160,6,'bakdlyorder','维度列','dlistfield','配置列',12,'NVARCHAR','DragableCheckBoxList','Height==200;data_appendgoodstrait==true;enabled==ptypeid',0,'',200,'机构★◎♂branchid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid,仓库★◎♂ktypeid',1,3) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 162,6,'__NotUse__','包含停用商品','containsstop','包含停用商品',7,'bit','','',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 161,6,'bakdlyorder','分布列明细','ddistdetailfield','显示字段',13,'NVARCHAR','CheckBoxList','Height==65;',0,'',200,'上市日期★◎♂startdate,过季日期★◎♂enddate,当前日期★◎♂nowdate,销售数量★◎♂saleqty,销售金额★◎♂saletotal,最高销量★◎♂maxqty,最高销售日期★◎♂maxsaledate,日均销量★◎♂avgdayqty,店均销量★◎♂avgstoreqty,在库数★◎♂stockqty,预计销售天数★◎♂daysqty',0,3) 
	
--7.采购汇总分析
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 181,7,'branch','分支机构','ctypeid','机构名称',1,'nvarchar','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=ktypeid;TypeName==rsCtype',0,'',60,'',0,1)
	
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 182,7,'stock','仓库','ktypeid','仓库',2,'nvarchar','TC','Tag==SELECTTYPE=7|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',60,'',0,1) 
	  
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 183,7,'btype','供应商','btypeid','供应商',3,'nvarchar','TC','Tag==SELECTTYPE=1|ISQUICKQUERY=1;TypeName==rsBtype',0,'',60,'',0,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 184,7,'employee','经手人','etypeid','经手人',4,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsEtype',0,'',60,'',0,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 185,7,'PriceType','售价类型','salepriceid','参考价格',7,'nchar','','',0,'',60,'参考价1★◎♂0,参考价2★◎♂1',0,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 186,7,'operationinfo','交易信息','opid','收货类型',8,'nvarchar','CheckBoxList','',0,'',60,'类型1★◎♂1,类型2★◎♂2',0,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 187,7,'operationinfo2','退货类型','opid2','退货类型',9,'nvarchar','CheckBoxList','',0,'',60,'退货类型1★◎♂1,发货类型2★◎♂2',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 188,7,'__NotUse__','开始日期','billdate_s','开始日期         ',5,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 189,7,'__NotUse__','截止日期','billdate_e','截止日期',6,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 190,7,'filter','价格过滤','filtertype','价格过滤',10,'char','','',0,'',0,'全部★◎♂0,非零单价★◎♂1,零单价★◎♂2',1,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 197,7,'__NotUse__','包含停用商品','containsstop','包含停用商品',11,'bit','','',0,'',0,'',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 191,7,'__NotUse__','商品全名','ptypeid','商品全名',12,'nvarchar','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2)
	 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 192,7,'ptypecategory','商品类别','ptypecategory','商品类别',13,'nvarchar','CheckBoxList','Height==65;',0,'',60,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2) 

INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 193,7,'__NotUse__','颜色','pcrec','颜色',14,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',60,'',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 194,7,'__NotUse__','尺码','psrec','尺码',15,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',60,'',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 195,7,'bakdlyorder','维度列','dlistfield','配置列',16,'','DragableCheckBoxList','Height==200;data_appendgoodstrait==true',0,'',0,'供应商★◎♂btypeid,经手人★◎♂etypeid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 196,7,'bakdlyorder','分布列明细','ddistdetailfield','显示字段',17,'','CheckBoxList','Height==70;',0,'',0,'采购数量★◎♂qty,采购金额★◎♂cgtotal,采购均价★◎♂buyprice,税额★◎♂taxtotal,含税单价★◎♂taxprice,价税合计★◎♂tax_total,参考金额★◎♂reprice,上市日期★◎♂startdate',1,3)
--8.库存周转率分析

 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 211,8,'branch','分支机构','branchid','机构名称',1,'nvarchar','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=ktypeid;TypeName==rsCtype',0,'',55,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 212,8,'stock','仓库','ktypeid','仓库',2,'nvarchar','TC','Tag==SELECTTYPE=7|PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1|HASTRANSFERSTOCK=1;TypeName==rsKtype',0,'',55,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 213,8,'__NotUse__','开始日期','billdate_s','开始日期',3,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 214,8,'__NotUse__','截止日期','billdate_e','截止日期',4,'date','','',0,'',0,'',1,1) 
-- INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
--	VALUES ( 215,8,'definetype','自定义类型','definetype','自定义类型	',5,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1) 
-- INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
--	VALUES ( 216,8,'definename','类型名称','definename','类型名称',6,'int','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1)
 
 --9.零售时段分析

 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 241,9,'branch','分支机构','branchid','机构名称',1,'NVARCHAR','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=ktypeid;TypeName==rsCtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 242,9,'stock','仓库','ktypeid','仓库',2,'NVARCHAR','TC','Tag==PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 243,9,'__NotUse__','开始日期','billdate_s','开始日期',3,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 244,9,'__NotUse__','截止日期','billdate_e','截止日期',4,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 245,9,'__NotUse__','开始时间','rangetime_s','开始时间		',5,'time','','IsSecondShow=False',0,'',0,'',1,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 246,9,'__NotUse__','截止时间','rangetime_e','截止时间',6,'time','','IsSecondShow=False',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 247,9,'__NotUse__','时间间隔','timespace','时间间隔',7,'INT','','',0,'',0,'0.5小时★◎♂30,1小时★◎♂60,2小时★◎♂120,3小时★◎♂180,4小时★◎♂240',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 248,9,'PriceType','售价类型','salepriceid','参考价格',8,'NVARCHAR','','',0,'',0,'必写1★◎♂0,必写2★◎♂1',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 249,9,'__NotUse__','包含停用商品','containsstop','包含停用商品',9,'bit','','',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 252,9,'__NotUse__','商品','ptypeid','商品全名',10,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2) 
  INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 251,9,'ptypecategory','商品类别','ptypecategory','商品类别',11,'NVARCHAR','CheckBoxList','Height==65;',0,'',60,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 253,9,'__NotUse__','颜色','colorid','颜色',12,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 254,9,'__NotUse__','尺码','sizeid','尺码',13,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 255,9,'bakdlyorder','维度列','dlistfield','配置列',15,'NVARCHAR','DragableCheckBoxList','Height==280;data_appendgoodstrait==true',0,'',400,'机构★◎♂branchid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 256,9,'bakdlyorder','分布列明细','ddistdetailfield','显示字段',16,'NVARCHAR','CheckBoxList','Height==65;',0,'',400,'销售数量★◎♂qty,销售金额★◎♂total',1,3) 

 --10.商品售罄率分析
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 275,10,'branch','机构','branchid','机构名称',1,'NVARCHAR','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=ktypeid;TypeName==rsCtype',0,'',60,'',0,1) 
  INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 283,10,'stock','仓库','ktypeid','仓库',2,'NVARCHAR','TC','Tag==SELECTTYPE=7|PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 271,10,'__NotUse__','开始日期','billdate_s','开始日期',3,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 272,10,'__NotUse__','截止日期','billdate_e','截止日期',4,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 273,10,'__NotUse__','上市开始日期','publishtime_s','上市开始日期',5,'date','','',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 274,10,'__NotUse__','上市结束日期','publishtime_e','上市结束日期    ',6,'date','','',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 276,10,'definetype','自定义类型','definetype','自定义类型',7,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 277,10,'definename','类型名称','definename','类型名称',8,'NVARCHAR','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',60,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 284,10,'__NotUse__','包含停用商品','containsstop','包含停用商品',9,'bit','','',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 278,10,'__NotUse__','商品','ptypeid','商品全名',10,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 279,10,'ptypecategory','商品类别','ptypecategory','商品类别',11,'NVARCHAR','CheckBoxList','Height==65;',0,'',400,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 280,10,'__NotUse__','颜色','colorid','颜色',12,'NVARCHAR','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',60,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 281,10,'__NotUse__','尺码','sizeid','尺码',13,'NVARCHAR','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',60,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 282,10,'bakdlyorder','维度列','dlistfield','配置列',14,'NVARCHAR','DragableCheckBoxList','Height==200;data_appendgoodstrait==true',0,'',400,'商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3) 


--11.销售状况表
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 301,11,'branch','机构名称','ctypeid','机构名称',2,'int','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid;TypeName==rsCtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 302,11,'stock','仓库','ktypeid','仓库',3,'int','TC','Tag==SELECTTYPE=7|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 303,11,'btype','客户','Btypeid','客户',3,'int','TC','Tag==SELECTTYPE=2|ISQUICKQUERY=1;TypeName==rsBtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 304,11,'employee','经手人','etypeid','经手人',4,'int','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1;TypeName==rsEtype',0,'',0,'',0,1)  
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 305,11,'PriceType','售价类型','salepriceid','参考价格',7,'char','','',0,'',0,'必写1★◎♂0,必写2★◎♂1',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 306,11,'__NotUse__','开始日期','billdate_s','开始日期   ',6,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 307,11,'__NotUse__','截止日期','billdate_e','截止日期   ',7,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 308,11,'__NotUse__','包含停用商品','containsstop','包含停用商品',12,'bit','','',0,'',0,'',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 309,11,'__NotUse__','商品全名','ptypeid','商品全名',13,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 310,11,'ptypecategory','商品类别','ptypecategory','商品类别',14,'int','CheckBoxList','Height==65;',0,'',0,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 311,11,'bakdlyorder','配置列','dlistfield','配置列',15,'int','DragableCheckBoxList','data_appendgoodstrait==true',0,'',0,'客户★◎♂btypeid,机构★◎♂branchid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 312,11,'bakdlyorder','显示字段','ddistdetailfield','显示字段',16,'int','CheckBoxList','Height==65;',0,'',0,'销售数量★◎♂saleqty,销售金额★◎♂saletotal,销售均价★◎♂saleprice,税额★◎♂taxtotal,含税单价★◎♂taxprice,抽成额★◎♂cctotal,价税合计★◎♂price_taxtotal,参考金额★◎♂retailtotal',0,3) 

--12.客户上货情况综合分析
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 331,12,'branch','机构名称','branchid','机构名称',2,'NVARCHAR','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid;TypeName==rsCtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 332,12,'stock','仓库','ktypeid','仓库',3,'NVARCHAR','TC','Tag==SELECTTYPE=7|PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 333,12,'operationinfo1','发货类型','opid1','发货类型',4,'NVARCHAR','CheckBoxList','',0,'',200,'发货类型1★◎♂1,发货类型2★◎♂2',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 334,12,'operationinfo2','退货类型','opid2','退货类型',5,'NVARCHAR','CheckBoxList','',0,'',200,'退货类型1★◎♂1,发货类型2★◎♂2',0,1)  
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 335,12,'__NotUse__','开始日期','billdate_s','开始日期   ',6,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 336,12,'__NotUse__','截止日期','billdate_e','截止日期   ',7,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 337,12,'definetype','自定义类型','definetype','自定义类型   ',10,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 338,12,'definename','类型名称','definename','类型名称',11,'NVARCHAR','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 339,12,'__NotUse__','包含停用商品','containsstop','包含停用商品',12,'bit','','',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 340,12,'__NotUse__','商品全名','ptypeid','商品全名',13,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 341,12,'ptypecategory','商品类别','ptypecategory','商品类别',14,'NVARCHAR','CheckBoxList','Height==65;',0,'',400,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
        VALUES ( 342,12,'__NotUse__','颜色','colorid','颜色',17,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
        VALUES ( 343,12,'__NotUse__','尺码','sizeid','尺码',18,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 344,12,'bakdlyorder','配置列','dlistfield','配置列',15,'NVARCHAR','DragableCheckBoxList','data_appendgoodstrait==true;enabled==ptypeid',0,'',400,'商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 345,12,'bakdlyorder','显示字段','ddistdetailfield','显示字段',16,'NVARCHAR','CheckBoxList','Height==65;',0,'',400,'首次入库日期★◎♂firstrkdate,首次发货日期★◎♂firstphdate,到配时差★◎♂dpdays,当前日期★◎♂nowdate,过季日期★◎♂enddate,进货数★◎♂inqty,销售数★◎♂saleqty,库存数★◎♂stockqty,上货客户数★◎♂upcustomer,上货数★◎♂upqty,补货客户数★◎♂bhcustomer,补货数★◎♂bhqty,退货客户数★◎♂thcustomer,退货数★◎♂thqty',0,3) 
	
--14 销售订单明细分析
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 391,14,'__NotUse__','查询方式','querymethod','查询方式',-1,'char','','',0,'',0,'商品★◎♂ptypeid,经手人★◎♂etypeid,客户★◎♂btypeid',1,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 392,14,'branch','分支机构','ctypeid','机构名称',2,'int','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid,etypeid;TypeName==rsCtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 393,14,'btype','往来单位','btypeid','客户',3,'int','TC','Tag==SELECTTYPE=34|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsBtype;',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 394,14,'stock','仓库','ktypeid','仓库',4,'int','TC','Tag==PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 395,14,'employee','雇员','etypeid','经手人',5,'int','TC','Tag==ISQUICKQUERY=1|PARENTCONTROL=ctypeid;TypeName==rsEtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 396,14,'operationinfo','交易信息','opid','发货类型',10,'int','CheckBoxList','',0,'',0,'类型1★◎♂1,类型2★◎♂2',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 397,14,'PriceType','售价类型','salepriceid','参考价格',11,'char','','',0,'',0,'必写1★◎♂0,必写2★◎♂1',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 398,14,'__NotUse__','录单开始日期','billdate_s','录单开始日期',6,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 399,14,'__NotUse__','录单截止日期','billdate_e','录单截止日期',7,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 400,14,'__NotUse__','发货开始日期','checktime_s','发货开始日期',8,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 401,14,'__NotUse__','发货截止日期','checktime_e','发货截止日期',9,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 402,14,'__NotUse__','审核状态','ifaudit','审核状态',13,'char','CheckBoxList','Height==60;',0,'',0,'全部审核★◎♂0,未审核★◎♂1,审核未通过★◎♂2',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 403,14,'definetype','自定义类型','definetype','自定义类型   ',14,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 404,14,'definename','类型名称','definename','类型名称',15,'int','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 405,14,'__NotUse__','包含停用商品','containsstop','包含停用商品',1,'bit','','',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 406,14,'__NotUse__','商品','ptypeid','商品全名',2,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsPtype',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 407,14,'bakdlyorder','分布列明细','ddistdetailfield','显示字段',1,'int','CheckBoxList','Height==350;',0,'',0,'订货数量★◎♂dhqty,订货报价★◎♂bjprice,订货金额★◎♂alltotal,订货参考单价★◎♂dhrefprice,订货参考金额★◎♂dhreftotal,,订货折扣(%)★◎♂dhdiscount,订货无税单价★◎♂dhprice,订货含税单价★◎♂dhtaxprice,订货无税金额★◎♂dhtotal,订货含税金额★◎♂dhtax_total,订货税率★◎♂dhtax1,订货税额★◎♂dhtaxtotal,订货折扣额★◎♂dhdiscounttotal,发货数量★◎♂tpqty,发货含税金额★◎♂tptax_total,发货参考金额★◎♂tpreftotal,终止数量★◎♂endqty,终止含税金额★◎♂endtax_total,终止参考金额★◎♂endreftotal,未发货数量★◎♂notqty,未发货含税金额★◎♂nottax_total,未发货参考金额★◎♂notreftotal,到货率(%)★◎♂topercent,完成率(%)★◎♂endpercent',0,3)
 
 --15 配货单汇总分析
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 421,15,'branch','配货机构','branchid_ph','配货机构',1,'nvarchar','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=ktypeid_ph;TypeName==rsCtype',0,'',60,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 422,15,'branch','申请机构','branchid_sq','申请机构',2,'nvarchar','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=ktypeid_sq;TypeName==rsCtype',0,'',60,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 423,15,'stock','配货仓库','ktypeid_ph','配货仓库',3,'nvarchar','TC','Tag==SELECTTYPE=7|PARENTCONTROL=branchid_ph|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',60,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 424,15,'stock','申请仓库','ktypeid_sq','申请仓库',4,'nvarchar','TC','Tag==PARENTCONTROL=branchid_sq|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',60,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 425,15,'employee','经手人','etypeid','经手人',5,'nvarchar','TC','Tag==SELECTTYPE=0|ISQUICKQUERY=1|PARENTCONTROLID=00000;TypeName==rsEtype',0,'',60,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 426,15,'billtype', '单据类型','vchtypeid','单据类型',6,'nvarchar','','',0,'',60,'单据类型1★◎♂0,单据类型2★◎♂1',1,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 441,15,'ywtype', '业务类型','opid','业务类型',7,'nvarchar', 'CheckBoxList','',0,'',60,'配货★◎♂1,退货★◎♂2,调配★◎♂3',    0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 427,15,'sendtype', '发货类型','sendtype',   '发货类型',8,'nvarchar', 'CheckBoxList','',0,'',60,'类型1★◎♂1,类型2★◎♂2',    0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 428,15,'backtype', '退货类型','backtype',   '退货类型',9,'nvarchar', 'CheckBoxList','',0,'',60,'类型1★◎♂1,类型2★◎♂2',    0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 429,15,'__NotUse__','包含差额调整','containdifftotal','包含差额调整',10,'bit','',            '',0,'',0,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 430,15,'pricetype','售价类型','salepriceid','参考价格',11,'nchar','',            '',0,'',60,'参考价1★◎♂0,参考价2★◎♂1',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 431,15,'__NotUse__','开始日期','billdate_s','开始日期',12,'date','','',0,'',0,'',1,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 432,15,'__NotUse__','截止日期','billdate_e','截止日期',13,'date','','',0,'',0,'',1,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 433,15,'definetype','自定义类型','definetype','自定义类型',14,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 434,15,'definename','类型名称','definename','类型名称',15,'nvarchar','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',60,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 442,15,'__NotUse__','包含停用商品','containsstop','包含停用商品',16,'bit','','',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 435,15,'__NotUse__','商品全名','ptypeid','商品全名',17,'nvarchar','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 436,15,'ptypecategory','商品类别','ptypecategory','商品类别',18,'nvarchar','CheckBoxList','',0,'',60,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 437,15,'__NotUse__','颜色','pcrec','颜色',19,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',60,'',0,2)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 438,15,'__NotUse__','尺码','psrec','尺码',20,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',60,'',0,2)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 439,15,'bakdlyorder','维度列','dlistfield','配置列',21,'','DragableCheckBoxList','Height==200;data_appendgoodstrait==true',0,'',0,'配货机构★◎♂branchid2,申请机构★◎♂branchid,经手人★◎♂etypeid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
  VALUES ( 440,15,'bakdlyorder','分布列明细','ddistdetailfield','显示字段',22,'','CheckBoxList','Height==70;',0,'',0,'配货数量★◎♂qty_1,配货辅助数量★◎♂aidqty_1,配货参考金额★◎♂total_1,配货占比(%)★◎♂percent_1,退货数量★◎♂qty_2,退货辅助数量★◎♂aidqty_2,退货参考金额★◎♂total_2,退货占比(%)★◎♂percent_2,实配数量★◎♂qty_3,实配辅助数量★◎♂aidqty_3,实配参考金额★◎♂total_3,实配占比(%)★◎♂percent_3,',1,3 )



 --16.配货申请单明细分析
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 451,16,'phctypeid','配货机构','phctypeid','配货机构',1,'int','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=phktypeid;TypeName==rsCtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 452,16,'sqctypeid','申请机构','sqctypeid','申请机构',2,'int','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=sqktypeid;TypeName==rsCtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 453,16,'phktypeid','配货仓库','phktypeid','配货仓库',3,'int','TC','Tag==SELECTTYPE=7|PARENTCONTROL=phctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 454,16,'sqktypeid','申请仓库','sqktypeid','申请仓库',4,'int','TC','Tag==SELECTTYPE=15|PARENTCONTROL=sqctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 455,16,'queryway','查询方式','queryway','查询方式',5,'int','DropDownEdit','',0,'',0,'商品★◎♂1,经手人★◎♂2,申请机构★◎♂3',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 456,16,'employee','经手人','etypeid','经手人',6,'int','TC','Tag==SELECTTYPE=0|ISQUICKQUERY=1;TypeName==rsEtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 457,16,'vchtype','单据类型','vchtype','单据类型',7,'int','DropDownEdit','',0,'',0,'配货申请单★◎♂1,退货申请单★◎♂2,调配申请单★◎♂3,加盟商配货订单★◎♂4,加盟商退货申请单★◎♂5',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 458,16,'opid1','发货类型','opid1','发货类型',8,'int','CheckBoxList','',0,'',0,'发货类型1★◎♂1,发货类型2★◎♂2',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 459,16,'opid2','退货类型','opid2','退货类型',9,'int','CheckBoxList','',0,'',0,'退货类型1★◎♂1,发货类型2★◎♂2',0,1)  
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 460,16,'PriceType','参考价格','salepriceid','参考价格',10,'char','','',0,'',0,'参考价格l★◎♂0,参考价格2★◎♂1',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 461,16,'__NotUse__','录单开始日期','billdate_s','录单开始日期   ',11,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 462,16,'__NotUse__','录单截止日期','billdate_e','录单截止日期   ',12,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 463,16,'checktime_s','交货开始日期','checktime_s','交货开始日期   ',13,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 464,16,'checktime_e','交货截止日期','checktime_e','交货截止日期   ',14,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 465,16,'__NotUse__','审核状态','ifaudit','审核状态',15,'char','CheckBoxList','Height==60;',0,'',0,'全部审核★◎♂0,未审核★◎♂1,审核未通过★◎♂2',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 466,16,'definetype','自定义类型','definetype','自定义类型   ',16,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 467,16,'definename','类型名称','definename','类型名称',17,'int','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 468,16,'__NotUse__','包含停用商品','containsstop','包含停用商品',18,'bit','','',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 469,16,'__NotUse__','商品全名','ptypeid','商品全名',19,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',0,'',0,2) 
 
/*
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 470,16,'bakdlyorder','配置列','dlistfield','配置列',20,'int','DragableCheckBoxList','data_appendgoodstrait==true;enabled==ptypeid',0,'',0,'申请机构-branchid,经手人-etypeid,机构-branchid2',1,3) 

*/

 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 471,16,'bakdlyorder','显示字段','ddistdetailfield','显示字段',21,'int','CheckBoxList','Height==65;',0,'',0,'数量★◎♂dhqty,报价★◎♂dhprice,金额★◎♂dhtotal,折扣%★◎♂dhdiscount,折后单价★◎♂dhzhprice,折后金额★◎♂dhzhtotal,参考单价★◎♂dhrefprice,参考金额★◎♂dhreftotal,配货率★◎♂phrate,完成率★◎♂finishrate',0,3) 


 --销售收款统计
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES (481,17,'branch','分支机构','branchid','机构名称',1,'NVARCHAR','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=etypeid;TypeName==rsCtype',0,'',60,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES (482,17,'employee','经手人','etypeid','经手人',4,'NVARCHAR','TC','Tag==SELECTTYPE=0|PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsEtype',0,'',60,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES (483,17,'ordermaker','制单人','etypeid2','制单人',4,'NVARCHAR','TC','Tag==SELECTTYPE=1|ISQUICKQUERY=1;TypeName==rsEtype',0,'',60,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES (485,17,'__NotUse__','开始日期','billdate_s','开始日期',5,'date','','',0,'',0,'',1,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES (486,17,'__NotUse__','截止日期','billdate_e','截止日期',6,'date','','',0,'',0,'',1,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES (487,17,'vchtypeid','交易信息','vchtypeid','销售类型',8,'NVARCHAR','CheckBoxList','',0,'',200,'批发★◎♂1,零售★◎♂2,加盟商配货★◎♂3',0,1)
	

--销售订单汇总分析
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (511,18,'branch','机构名称','branchid','机构名称',1,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=ktypeid,btypeid;TypeName==rsCtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (512,18,'btype','往来单位','btypeid','客户名称',2,'int','TC','Tag==SELECTTYPE=34|PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsBtype;',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (513,18,'employee','经手人','etypeid','经手人',3,'int','TC','Tag==SELECTTYPE=0|ISQUICKQUERY=1;TypeName==rsEtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (514,18,'ktype','仓库','ktypeid','仓库名称',4,'int','TC','Tag==PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (515,18,'sendtype','发货类型','sendtype','发货类型',5,'int','CheckBoxList','',0,'',0,'类型1★◎♂1,类型2★◎♂2',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (516,18,'pricetype','售价类型','salepriceid','参考价格',6,'char','','',0,'',0,'参考价1★◎♂0,参考价2★◎♂1',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (517,18,'__NotUse__','开始日期','billdate_s','录单开始日期',7,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (518,18,'__NotUse__','截止日期','billdate_e','录单截止日期',8,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (519,18,'__NotUse__','开始日期','trandate_s','交货开始日期',9,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (520,18,'__NotUse__','截止日期','trandate_e','交货截止日期',10,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (521,18,'__NotUse__','审核状态','billstate','审核状态',11,'int','CheckBoxList','',0,'',0,'参考价1★◎♂0,参考价2★◎♂1',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (522,18,'definetype','自定义类型','definetype','自定义类型',12,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (523,18,'definename','类型名称','definename','类型名称',13,'int','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (524,18,'__NotUse__','商品全名','ptypeid','商品全名',14,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (525,18,'ptypecategory','商品类别','ptypecategory','商品类别',15,'int','CheckBoxList','',0,'',0,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (526,18,'__NotUse__','颜色','pcrec','颜色',16,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (527,18,'__NotUse__','尺码','psrec','尺码',17,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (528,18,'bakdlyorder','维度列','dlistfield','配置列',18,'int','DragableCheckBoxList','Height==200;data_appendgoodstrait==true',0,'',0,'客户★◎♂btypeid,机构★◎♂branchid,经手人★◎♂etypeid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (529,18,'bakdlyorder','分布列明细','ddistdetailfield','显示字段',19,'int','CheckBoxList','Height==70;',0,'',0,'订货数量★◎♂dhsl,订货报价★◎♂dhbj,订货金额★◎♂dhje,参考订货单价★◎♂ckdhdj,订货参考金额★◎♂dhckje,订货折扣★◎♂dhzk,订货无税单价★◎♂dhwsdj,订货含税单价★◎♂dhhsdj,订货无税金额★◎♂dhwsje,订货税率★◎♂dhsl1,订货税额★◎♂dhse,订货含税金额★◎♂dhhsje,订货折扣额★◎♂dhzke,发货数量★◎♂fhsl,发货含税金额★◎♂fhhsje,发货参考金额★◎♂fhckje,终止数量★◎♂zzsl,终止含税金额★◎♂zzhsje,终止参考金额★◎♂zzckje,未发货数量★◎♂wfhsl,未发货含税金额★◎♂wfhhsje,未发货参考金额★◎♂wfhckje,发货率★◎♂fhl,完成率★◎♂wcl',1,3)
 
 


 --20.供应商供货准时分析
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 571,20,'phctypeid','机构','branchid','机构',1,'int','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid;TypeName==rsCtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 572,20,'btype','供应商','btypeid','供应商',3,'int','TC','Tag==SELECTTYPE=1|PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsBtype;',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
        VALUES ( 573,20,'employee','经手人','etypeid','经手人',3,'int','TC','Tag==SELECTTYPE=0|ISQUICKQUERY=1;TypeName==rsEtype',0,'',0,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
        VALUES ( 574,20,'ktype','仓库','ktypeid','仓库',4,'int','TC','Tag==PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',0,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 575,20,'opid1','收货类型','opid1','收货类型',8,'int','CheckBoxList','',0,'',0,'发货类型1★◎♂1,发货类型2★◎♂2',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 576,20,'__NotUse__','录单开始日期','billdate_s','录单开始日期   ',11,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 577,20,'__NotUse__','录单截止日期','billdate_e','录单截止日期   ',12,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 578,20,'checktime_s','交货开始日期','checktime_s','交货开始日期   ',13,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 579,20,'checktime_e','交货截止日期','checktime_e','交货截止日期   ',14,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 580,20,'definetype','自定义类型','definetype','自定义类型   ',16,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 581,20,'definename','类型名称','definename','类型名称',17,'int','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 582,20,'PriceType','参考价格','salepriceid','参考价格',10,'char','','',0,'',0,'参考价格l★◎♂0,参考价格2★◎♂1',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 583,20,'__NotUse__','包含停用商品','containsstop','包含停用商品',18,'bit','','',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 584,20,'__NotUse__','商品全名','ptypeid','商品全名',19,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 585,20,'bakdlyorder','显示字段','ddistdetailfield','显示字段',21,'int','CheckBoxList','Height==65;',0,'',0,'订单数量★◎♂ddqty,订单金额★◎♂ddtotal,准时交货数量★◎♂zsjhqty,准时交货金额★◎♂zsjhtotal,准时交货率★◎♂zsjhl,延时交货数量★◎♂ysjhqty,延时交货金额★◎♂ysjhtotal,延时交货率★◎♂ysjhl,终止数量★◎♂endqty,终止金额★◎♂endtotal,到货数量★◎♂getqty,到货金额★◎♂gettotal,已付款金额★◎♂yfktotal,未付款金额★◎♂wfktotal',0,3) 


--21 零售对比分析
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES (601,21,'branch','分支机构','branchid','机构名称',1,'NVARCHAR','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1;TypeName==rsCtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
VALUES (602,21,'__NotUse__','上期开始日期','checktime_s','上期开始日期',2,'date','','',0,'',0,'',1,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
VALUES (603,21,'__NotUse__','上期截止日期','checktime_e','上期截止日期',3,'date','','',0,'',0,'',1,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES (604,21,'__NotUse__','本期开始日期','billdate_s','本期开始日期',4,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES (605,21,'__NotUse__','本期截止日期','billdate_e','本期截止日期',5,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
VALUES (606,21,'PriceType','售价类型','salepriceid','参考价格',6,'nchar','','',0,'',60,'参考价1★◎♂0,参考价2★◎♂1',0,1) 
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES (607,21,'__NotUse__','排名标准','rankmode','排名标准',7,'nvarchar','RADIOBUTTONLIST','',0,'',2,'0=金额,1=数量',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
VALUES (608,21,'definetype','自定义类型','definetype','自定义类型   ',8,'nchar','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
VALUES (609,21,'definename','类型名称','definename','类型名称',9,'nchar','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1) 
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES (610,21,'__NotUse__','包含停用商品','containsstop','包含停用商品',10,'bit','','',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
VALUES (611,21,'__NotUse__','商品','ptypeid','商品全名',11,'nvarchar','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
VALUES (612,21,'ptypecategory','商品类别','ptypecategory','商品类别',12,'nvarchar','CheckBoxList','Height==65;',0,'',100,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES (613,21,'__NotUse__','颜色','colorid','颜色',13,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES (614,21,'__NotUse__','尺码','sizeid','尺码',14,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES (615,21,'__NotUse__','维度列','dlistfield','配置列',15,'','DragableCheckBoxList','Height==280;data_appendgoodstrait==true',0,'',0,'机构★◎♂branchid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)

--22 价格变迁零售统计
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (631,22,'branch','机构名称','branchid','机构名称',1,'NVARCHAR','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=ktypeid,btypeid;TypeName==rsCtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (632,22,'__NotUse__','开始日期','billdate_s','开始日期',2,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (633,22,'__NotUse__','截止日期','billdate_e','截止日期',3,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (635,22,'__NotUse__','折扣起始','discount_e','折扣起始',4,'int','','',0,'',0,'100%★◎♂100,90%★◎♂90,80%★◎♂80,70%★◎♂70,60%★◎♂60,50%★◎♂50,40%★◎♂40,30%★◎♂30,20%★◎♂20,10%★◎♂10,0%★◎♂0',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (636,22,'__NotUse__','折扣截止','discount_s','折扣截止',5,'int','','',0,'',0,'100%★◎♂100,90%★◎♂90,80%★◎♂80,70%★◎♂70,60%★◎♂60,50%★◎♂50,40%★◎♂40,30%★◎♂30,20%★◎♂20,10%★◎♂10,0%★◎♂0',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (637,22,'__NotUse__','折扣档','discount_l','折扣档',6,'int','','',0,'',0,'5%★◎♂5,10%★◎♂10,15%★◎♂15,20%★◎♂20,25%★◎♂25,30%★◎♂30',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (638,22,'definetype','自定义类型','definetype','自定义类型',7,'INT','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (639,22,'definename','类型名称','definename','类型名称',8,'NVARCHAR','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
 VALUES (640,22,'__NotUse__','包含停用商品','containsstop','包含停用商品',9,'bit','','',0,'',0,'',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (641,22,'__NotUse__','商品全名','ptypeid','商品全名',10,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (642,22,'ptypecategory','商品类别','ptypecategory','商品类别',11,'NVARCHAR','CheckBoxList','',0,'',60,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (643,22,'__NotUse__','颜色','pcrec','颜色',12,'INT','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (644,22,'__NotUse__','尺码','psrec','尺码',13,'INT','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (645,22,'bakdlyorder','维度列','dlistfield','配置列',14,'NVARCHAR','DragableCheckBoxList','Height==200;data_appendgoodstrait==true',0,'',600,'机构★◎♂branchid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (646,22,'bakdlyorder','分布列明细','ddistdetailfield','显示字段',15,'NVARCHAR','CheckBoxList','Height==70;',0,'',600,'销售数量★◎♂qty,销售金额★◎♂total,毛利额★◎♂mle',1,3)

--23 配货申请单汇总分析
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (661,23,'branch','配货机构','branchid_ph','配货机构',1,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=ktypeid_ph;TypeName==rsCtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (662,23,'branch','申请机构','branchid_sq','申请机构',2,'int','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=ktypeid_sq;TypeName==rsCtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (663,23,'stock','配货仓库','ktypeid_ph','配货仓库',3,'int','TC','Tag==PARENTCONTROL=branchid_ph|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (664,23,'stock','申请仓库','ktypeid_sq','申请仓库',4,'int','TC','Tag==PARENTCONTROL=branchid_sq|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (665,23,'employee','经手人','etypeid','经手人',5,'int','TC','Tag==SELECTTYPE=0|ISQUICKQUERY=1;TypeName==rsEtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (666,23,'billtype','单据类型','vchtypeid','单据类型',6,'char','','',0,'',0,'单据类型1★◎♂0,单据类型2★◎♂1',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (667,23,'sendtype','发货类型','sendtype','发货类型',7,'int','CheckBoxList','',0,'',0,'类型1★◎♂1,类型2★◎♂2',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (668,23,'backtype','退货类型','backtype','退货类型',8,'int','CheckBoxList','',0,'',0,'类型1★◎♂1,类型2★◎♂2',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (670,23,'pricetype','售价类型','salepriceid','参考价格',10,'char','','',0,'',0,'参考价1★◎♂0,参考价2★◎♂1',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (671,23,'__NotUse__','录单开始日期','billdate_s','录单开始日期',11,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (672,23,'__NotUse__','录单截止日期','billdate_e','录单截止日期',12,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (673,23,'__NotUse__','交货开始日期','jhdate_s','交货开始日期',13,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (674,23,'__NotUse__','交货截止日期','jhdate_e','交货截止日期',14,'date','','',0,'',0,'',1,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (675,23,'__NotUse__','审核状态','ifaudit','审核状态',15,'char','CheckBoxList','Height==60;',0,'',0,'全部审核★◎♂0,未审核★◎♂1,审核未通过★◎♂2',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (676,23,'definetype','自定义类型','definetype','自定义类型',16,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (677,23,'definename','类型名称','definename','类型名称',17,'int','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (678,23,'__NotUse__','商品全名','ptypeid','商品全名',18,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (679,23,'ptypecategory','商品类别','ptypecategory','商品类别',19,'int','CheckBoxList','',0,'',0,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (680,23,'__NotUse__','颜色','pcrec','颜色',20,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (681,23,'__NotUse__','尺码','psrec','尺码',21,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (682,23,'bakdlyorder','维度列','dlistfield','配置列',22,'int','DragableCheckBoxList','Height==200;data_appendgoodstrait==true',0,'',0,'配货机构★◎♂branchid2,申请机构★◎♂branchid,经手人★◎♂etypeid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (683,23,'bakdlyorder','分布列明细','ddistdetailfield','显示字段',23,'int','CheckBoxList','Height==70;',0,'',0,'数量★◎♂qty,报价★◎♂price,金额★◎♂total,折扣★◎♂discount,折后单价★◎♂zhdj,折后金额★◎♂zhje,参考单价★◎♂ckdj,参考金额★◎♂ckje,配货率★◎♂phl,完成率★◎♂wcl',1,3)



--24.零售单汇总分析
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 691,24,'branch','机构名称','ctypeid','机构',1,'int','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1;TypeName==rsCtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 692,24,'PriceType','参考价格','salepriceid','参考价格',2,'char','','',0,'',0,'参考价格l★◎♂0,参考价格2★◎♂1',1,1)  
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 693,24,'__NotUse__','开始日期','billdate_s','开始日期   ',3,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 694,24,'__NotUse__','截止日期','billdate_e','截止日期   ',4,'date','','',0,'',0,'',1,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 695,24,'vchtype','单据类型','vchtype','单据类型',5,'int','TC','Tag==ISQUICKQUERY=1|SQLFORWHERE= AND Vchtype IN(12,100);TypeName==rsVtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 696,24,'definetype','自定义类型','definetype','自定义类型   ',6,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 697,24,'definename','类型名称','definename','类型名称',7,'int','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 698,24,'__NotUse__','商品全名','ptypeid','商品全名',8,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 699,24,'ptypecategory','商品类别','ptypecategory','商品类别',9,'int','CheckBoxList','Height==65;',0,'',0,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 700,24,'__NotUse__','颜色','colorid','颜色',10,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 701,24,'__NotUse__','尺码','sizeid','尺码',11,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 702,24,'bakdlyorder','配置列','dlistfield','配置列',12,'int','DragableCheckBoxList','data_appendgoodstrait==true',0,'',0,'机构★◎♂branchid,经手人★◎♂etypeid,商品分类★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 703,24,'bakdlyorder','显示字段','ddistdetailfield','显示字段',13,'int','CheckBoxList','Height==65;',0,'',0,'数量★◎♂djqty,报价★◎♂djprice,金额★◎♂djtotal,折扣%★◎♂djdiscount,折后单价★◎♂discountprice,折后金额★◎♂discounttotal,vip折扣%★◎♂vipdiscount,成交金额★◎♂cjtotal,抽成额★◎♂cctotal,参考单价★◎♂refprice,参考金额★◎♂reftotal',0,3) 

--25.商品零售分析
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 721,25,'branch','机构名称','ctypeid','机构',1,'int','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=ktypeid;TypeName==rsCtype',0,'',0,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
	VALUES (722,25,'ktype','仓库','ktypeid','仓库名称',2,'int','TC','Tag==PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',0,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 723,25,'PriceType','参考价格','salepriceid','参考价格',3,'char','','',0,'',0,'参考价格l★◎♂0,参考价格2★◎♂1',1,1)  
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 724,25,'__NotUse__','开始日期','billdate_s','开始日期   ',4,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 725,25,'__NotUse__','截止日期','billdate_e','截止日期   ',5,'date','','',0,'',0,'',1,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
	VALUES (726,25,'definetype','自定义类型','definetype','自定义类型',6,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
	VALUES (727,25,'definename','类型名称','definename','类型名称',7,'int','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 728,25,'__NotUse__','包含停用商品','containsstop','包含停用商品',8,'bit','','',0,'',0,'',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 729,25,'__NotUse__','商品全名','ptypeid','商品全名',9,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',0,'',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 730,25,'ptypecategory','商品类别','ptypecategory','商品类别',10,'int','CheckBoxList','Height==65;',0,'',0,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 731,25,'__NotUse__','颜色','pcrec','颜色',11,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 732,25,'__NotUse__','尺码','psrec','尺码',12,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 733,25,'bakdlyorder','配置列','dlistfield','配置列',13,'int','DragableCheckBoxList','data_appendgoodstrait==true;enabled==ptypeid',0,'',0,'机构★◎♂ctypeid,经手人★◎♂etypeid,商品分类★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES ( 734,25,'bakdlyorder','显示字段','ddistdetailfield','显示字段',14,'int','CheckBoxList','Height==65;',0,'',0,'销售数量★◎♂sqty,参考金额★◎♂sretotal,退货数量★◎♂tqty,退货参考金额★◎♂tretotal,实际销售数量★◎♂allqty,实际销售参考金额★◎♂allreftotal,平均折扣%★◎♂avgvipdiscount,平均单价★◎♂avgprice,价税合计★◎♂tax_total,抽成额★◎♂DeductTotal,税额★◎♂Taxtotal,毛利额★◎♂proTotal,毛利额占比%★◎♂topercent',0,3) 

--26	商品畅滞销分析
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (751,26,'branchtype','机构类型','branchtype','机构类型',1,'char','RADIOBUTTONLIST','',0,'',0,'0=内部机构,1=加盟机构',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (752,26,'branch','分支机构','branchid','分支机构',2,'int','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1;TypeName==rsCtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (753,26,'stock','仓    库','ktypeid','仓    库',3,'int','TC','Tag==PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (754,26,'__NotUse__','业务类型','businesstype','业务类型',4,'char','CheckBoxList','',0,'',0,'批发销售★◎♂0,零售★◎♂1,加盟配送★◎♂2',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (755,26,'__NotUse__','基数','percentnum','销售百分比基数',5,'char','radiobuttonlist','',0,'',0,'0=本期入库数,1=本期进货数,2=上期库存数+本期入库数,3=上期库存数+本期进货数',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (756,26,'__NotUse__','开始日期','goodsdate_s','上市开始日期   ',6,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (757,26,'__NotUse__','截止日期','goodsdate_e','上市截止日期   ',7,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (758,26,'__NotUse__','销售比例','salepercent_o','销售比例>=',8,'numeric','','',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (759,26,'__NotUse__','销售比例','salepercent_t','销售比例<=',9,'numeric','','',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (760,26,'__NotUse__','排行','topnum','显示排行前',10,'int','','',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (761,26,'__NotUse__','商品全名','ptypeid','商品全名',11,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (762,26,'ptypecategory','商品类别','ptypecategory','商品类别',12,'int','CheckBoxList','Height==65;',0,'',0,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (763,26,'__NotUse__','颜色','colorid','颜色',13,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (764,26,'__NotUse__','尺码','sizeid','尺码',14,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (765,26,'bakdlyorder','配置列','dlistfield','配置列',15,'int','DragableCheckBoxList','data_appendgoodstrait==true',0,'',0,'机构★◎♂branchid,商品分类★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (766,26,'bakdlyorder','显示字段','ddistdetailfield','显示字段',16,'int','CheckBoxList','Height==65;',0,'',0,'上市日期★◎♂issuedate,过季日期★◎♂stopdate,上期库存★◎♂preqty,本期入库数%★◎♂inqty,销售数量★◎♂saleqty,销售比例★◎♂salepercent,本期库存%★◎♂qty',0,3)

--27	供应商供货对照表
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (781,27,'branch','机构名称','branchid','机构名称',1,'NVARCHAR','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid;TypeName==rsCtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (782,27,'btype','供应商','btypeid','供应商',2,'NVARCHAR','TC','Tag==SELECTTYPE=1|ISQUICKQUERY=1;TypeName==rsBtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (783,27,'stock','仓库','ktypeid','仓库',3,'NVARCHAR','TC','Tag==SELECTTYPE=15|PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (784,27,'employee','经手人','etypeid','经手人',4,'NVARCHAR','TC','Tag==SELECTTYPE=0|ISQUICKQUERY=1;TypeName==rsEtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (785,27,'__NotUse__','查询方式','searchtype','查询方式',5,'int','dropdownedit','',0,'',0,'供货商★◎♂0,商品★◎♂1',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (786,27,'dlydata','收货类型','opid','收货类型',6,'NVARCHAR','checkboxlist','',0,'',400,'必写1★◎♂0,必写2★◎♂1',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (787,27,'__NotUse__','开始日期','billdate_s','开始日期   ',7,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (788,27,'__NotUse__','截止日期','billdate_e','截止日期   ',8,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (789,27,'definetype','自定义类型','definetype','自定义类型',9,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (790,27,'definename','类型名称','definename','类型名称',10,'NVARCHAR','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (791,27,'__NotUse__','包含停用商品','containsstop','包含停用商品',11,'bit','','',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (792,27,'__NotUse__','商品全名','ptypeid','商品全名',12,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2)


--28	零售单明细分析
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (811,28,'branch','机构名称','branchid','机构名称',1,'int','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid;TypeName==rsCtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (812,28,'PriceType','参考价格','salepriceid','参考价格',2,'char','dropdownedit','',0,'',0,'参考价格l★◎♂0,参考价格2★◎♂1',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (813,28,'__NotUse__','查询方式','searchtype','查询方式',3,'int','dropdownedit','',0,'',0,'机构★◎♂0,经手人★◎♂1,商品★◎♂2',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (814,28,'__NotUse__','开始日期','billdate_s','开始日期   ',4,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (815,28,'__NotUse__','截止日期','billdate_e','截止日期   ',5,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (816,28,'VchTpye','单据类型','vchtpyeid','单据类型',6,'char','dropdownedit','',0,'',0,'零售单★◎♂12,代销零售单★◎♂100',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (817,28,'definetype','自定义类型','definetype','自定义类型',7,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (818,28,'definename','类型名称','definename','类型名称',8,'int','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (819,28,'__NotUse__','商品全名','ptypeid','商品全名',9,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (821,28,'bakdlyorder','显示字段','ddistdetailfield','显示字段',11,'int','CheckBoxList','Height==65;',0,'',0,'数量★◎♂djqty,报价★◎♂djprice,金额★◎♂djtotal,折扣%★◎♂djdiscount,折后单价★◎♂discountprice,折后金额★◎♂discounttotal,vip折扣%★◎♂vipdiscount,成交金额★◎♂cjtotal,抽成额★◎♂cctotal,参考单价★◎♂refprice,参考金额★◎♂reftotal',1,3)


--29	供应商供货统计
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (841,29,'branch','机构','branchid','机构',1,'NVARCHAR','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid;TypeName==rsCtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (842,29,'ktype','仓库','ktypeid','仓库',2,'NVARCHAR','TC','Tag==PARENTCONTROL=branchid|SELECTTYPE=7|ISMUSTPARENT=1;TypeName==rsKtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (843,29,'btype','供应商','btypeid','供应商',3,'NVARCHAR','TC','Tag==SELECTTYPE=1;TypeName==rsBtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (844,29,'etype','经手人','etypeid','经手人',4,'NVARCHAR','TC','Tag==SELECTTYPE=0;TypeName==rsEtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (845,29,'PriceType','参考价格','salepriceid','参考价格',5,'NVARCHAR','dropdownedit','',0,'',60,'参考价格l★◎♂0,参考价格2★◎♂1',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (846,29,'OperationInfo','收货类型','opid2','收货类型',6,'NVARCHAR','checkboxlist','',0,'',400,'收货类型l★◎♂0,收货类型2★◎♂1',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (847,29,'OperationInfo','退货类型','opid3','退货类型',7,'NVARCHAR','checkboxlist','',0,'',400,'退货类型l★◎♂0,退货类型2★◎♂1',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (848,29,'__NotUse__','开始日期','billdate_s','开始日期',8,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (849,29,'__NotUse__','截止日期','billdate_e','截止日期',9,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (850,29,'__NotUse__','包含停用商品','containsstop','包含停用商品',10,'bit','','',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (851,29,'__NotUse__','商品全名','ptypeid','商品全名',11,'VARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rmPtype',0,'',8000,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (852,29,'bakdlyorder','显示字段','ddistdetailfield','显示字段',12,'NVARCHAR','CheckBoxList','Height==65;',0,'',400,'采购数量★◎♂qty,采购金额★◎♂total,税额★◎♂taxtotal,价税合计★◎♂tax_total,参考金额★◎♂retailtotal,采购比重%★◎♂jhbz',0,3)

--30	销售明细分析
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (871,30,'__NotUse__','分支机构','branchmode','机构模式',1,'nvarchar','RADIOBUTTONLIST','',0,'',2,'0=内部机构,1=加盟机构',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (872,30,'branch','机构','branchid','机构',2,'NVARCHAR','TC','Tag==SELECTTYPE=11|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid,etypeid;TypeName==rsCtype',0,'',60,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (873,30,'ktype','仓库','ktypeid','仓库',3,'NVARCHAR','TC','Tag==PARENTCONTROL=branchid|SELECTTYPE=27|ISMUSTPARENT=1;TypeName==rsKtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (874,30,'btype','客户','btypeid','客户',4,'NVARCHAR','TC','Tag==SELECTTYPE=2|PARENTCONTROL=branchid|ISMUSTPARENT=1;TypeName==rsBtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (875,30,'etype','经手人','etypeid','经手人',5,'NVARCHAR','TC','Tag==SELECTTYPE=1|PARENTCONTROL=branchid|ISMUSTPARENT=1;TypeName==rsEtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (876,30,'__NotUse__','查询方式','searchtype','查询方式',6,'int','dropdownedit','',0,'',0,'商品★◎♂0,客户★◎♂1,经手人★◎♂2',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (877,30,'VchTpye','单据类型','vchtypeid','单据类型',7,'NVARCHAR','checkboxlist','',0,'',60,'销售出库单★◎♂11,销售退货单★◎♂45,销售换货单★◎♂24',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (878,30,'OperationInfo','发货类型','opid1','发货类型',8,'NVARCHAR','checkboxlist','',0,'',200,'发货类型★◎♂0,发货类型★◎♂1',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (879,30,'OperationInfo','退货类型','opid3','退货类型',9,'NVARCHAR','checkboxlist','',0,'',200,'退货类型l★◎♂0,退货类型2★◎♂1',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (880,30,'__NotUse__','红冲单据','isred','单据状态',10,'nvarchar','','',0,'',60,'全部单据★◎♂0,显示红冲单据★◎♂T,不显示红冲单据★◎♂F',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (881,30,'PriceType','参考价格','salepriceid','参考价格',11,'NVARCHAR','dropdownedit','',0,'',60,'参考价格l★◎♂0,参考价格2★◎♂1',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (882,30,'__NotUse__','开始日期','billdate_s','开始日期',12,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (883,30,'__NotUse__','截止日期','billdate_e','截止日期',13,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (884,30,'definetype','自定义类型','definetype','自定义类型',14,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (885,30,'definename','类型名称','definename','类型名称',15,'NVARCHAR','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (886,30,'__NotUse__','包含停用商品','containsstop','包含停用商品',16,'bit','','',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (887,30,'__NotUse__','商品全名','ptypeid','商品全名',17,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (888,30,'bakdlyorder','显示字段','ddistdetailfield','显示字段',18,'NVARCHAR','CheckBoxList','Height==65;',0,'',200,'数量★◎♂qty,单价★◎♂price,金额★◎♂total,参考单价★◎♂refprice,参考金额★◎♂reftotal,折扣%★◎♂discount,折后单价★◎♂discountprice,折后金额★◎♂discounttotal,VIP折扣%★◎♂vipdiscount,折让★◎♂convert1,成交金额★◎♂bargaintotal,税率%★◎♂tax,税额★◎♂taxtotal,含税单价★◎♂taxprice,含税金额★◎♂salemoney',0,3)


--31	销售综合分析   
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (901,31,'__NotUse__','分支机构','branchmode','机构模式',1,'nvarchar','RADIOBUTTONLIST','',0,'',2,'0=内部机构,1=加盟机构',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (902,31,'branch','机构','branchid','机构',2,'NVARCHAR','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=ktypeid,etypeid;TypeName==rsCtype',0,'',60,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (903,31,'ktype','仓库','ktypeid','仓库',3,'NVARCHAR','TC','Tag==PARENTCONTROL=branchid|SELECTTYPE=31|ISMUSTPARENT=1;TypeName==rsKtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (904,31,'btype','客户','btypeid','客户',4,'NVARCHAR','TC','Tag==SELECTTYPE=14;TypeName==rsBtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (905,31,'etype','经手人','etypeid','经手人',5,'NVARCHAR','TC','Tag==SELECTTYPE=1|PARENTCONTROL=branchid|ISMUSTPARENT=1;TypeName==rsEtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (906,31,'PriceType','参考价格','salepriceid','参考价格',6,'NVARCHAR','dropdownedit','',0,'',60,'参考价格l★◎♂0,参考价格2★◎♂1',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (907,31,'__NotUse__','开始日期','billdate_s','开始日期',7,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (908,31,'__NotUse__','截止日期','billdate_e','截止日期',8,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (909,31,'saletype','销售类型','saletype','销售类型',9,'NVARCHAR','checkboxlist','',0,'',200,'批发销售★◎♂11-45-24,零售销售★◎♂12-100,加盟销售★◎♂222-224',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (910,31,'operationinfo','发货类型','opid1','发货类型',10,'NVARCHAR','CheckBoxList','',0,'',400,'类型1★◎♂1,类型2★◎♂2',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (911,31,'operationinfo2','退货类型','opid3','退货类型',11,'NVARCHAR','CheckBoxList','',0,'',400,'退货类型1★◎♂1,发货类型2★◎♂2',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (912,31,'definetype','自定义类型','definetype','自定义类型',12,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',200,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (913,31,'definename','类型名称','definename','类型名称',13,'NVARCHAR','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',200,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (914,31,'__NotUse__','包含停用商品','containsstop','包含停用商品',14,'bit','','',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (915,31,'ptypecategory','商品类别','ptypecategory','商品类别',15,'NVARCHAR','CheckBoxList','Height==65;',0,'',50,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (916,31,'__NotUse__','商品全名','ptypeid','商品全名',16,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',50,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (917,31,'__NotUse__','颜色','colorid','颜色',17,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (918,31,'__NotUse__','尺码','sizeid','尺码',18,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (919,31,'bakdlyorder','配置列','dlistfield','配置列',19,'NVARCHAR','DragableCheckBoxList','Height==180;data_appendgoodstrait==true',0,'',400,'客户★◎♂btypeid,机构★◎♂branchid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (920,31,'bakdlyorder','显示字段','ddistdetailfield','显示字段',20,'NVARCHAR','CheckBoxList','Height==65;',0,'',400,'销售数量★◎♂saleqty,销售金额★◎♂saletotal,销售均价★◎♂saleprice,税额★◎♂taxtotal,含税单价★◎♂taxprice,抽成额★◎♂cctotal,价税合计★◎♂tax_total,参考金额★◎♂reftotal,销售量比重%★◎♂xslbz,价税合计比重%★◎♂jshjbz',0,3)
 
--32	促销赠品分析
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1000,32,'branch','分支机构','ctypeid','机构名称',1,'nvarchar','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1;TypeName==rmCtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1001,32,'__NotUse__','开始日期','billdate_s','开始日期',2,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1002,32,'__NotUse__','截止日期','billdate_e','截止日期',3,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1003,32,'PriceType','售价类型','salepriceid','参考价格',4,'nchar','','',0,'',60,'必写1★◎♂0,必写2★◎♂1',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1004,32,'__NotUse__','促销方式','saletype','促销方式',5,'int','','',0,'',0,'全部★◎♂-1,整单促销★◎♂0,单品促销★◎♂1',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1005,32,'__NotUse__','商品','ptypeid','商品全名',8,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1010,32,'ptypecategory','商品类别','ptypecategory','商品类别',9,'nvarchar','CheckBoxList','Height==65;',0,'',60,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1006,32,'__NotUse__','颜色','colorid','颜色',10,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1007,32,'__NotUse__','尺码','sizeid','尺码',10,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1008,32,'DlyData','分布列明细','ddistdetailfield','显示字段',12,'','CheckBoxList','Height==350;',0,'',0,'数量★◎♂Qty,成交金额★◎♂Total,参考金额★◎♂dhreftotal,成本金额★◎♂costTotal,库存数量★◎♂stockQty',0,3)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1009,32,'DlyData','维度列','dlistfield','配置列',11,'','DragableCheckBoxList','Height==120;data_appendgoodstrait==true',0,'',0,'机构★◎♂branchid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)

--33   供应商供货准时分析
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1100,33,'branch','分支机构','ctypeid','机构名称',1,'nvarchar','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=ktypeid;TypeName==rsCtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1101,33,'btype','往来单位','btypeid','供应商',2,'nvarchar','TC','Tag==SELECTTYPE=1|ISQUICKQUERY=1;TypeName==rsBtype;',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1102,33,'stock','仓库','ktypeid','仓库',3,'nvarchar','TC','Tag==SELECTTYPE=7|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1103,33,'employee','雇员','etypeid','经手人',4,'nvarchar','TC','Tag==SELECTTYPE=0|ISQUICKQUERY=1;TypeName==rsEtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1105,33,'PriceType','售价类型','salepriceid','参考价格',6,'nchar','','',0,'',60,'必写1★◎♂0,必写2★◎♂1',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1106,33,'__NotUse__','录单开始日期','billdate_s','录单开始日期',7,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1107,33,'__NotUse__','录单截止日期','billdate_e','录单截止日期',8,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1108,33,'__NotUse__','交货开始日期','jhbilldate_s','交货开始日期',9,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1109,33,'__NotUse__','交货截止日期','jhbilldate_e','交货截止日期',10,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1110,33,'definetype','自定义类型','definetype','自定义类型   ',11,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1111,33,'definename','类型名称','definename','类型名称',12,'nvarchar','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1112,33,'__NotUse__','包含停用商品','containsstop','包含停用商品',13,'bit','','',0,'',0,'',0,2)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1113,33,'__NotUse__','商品','ptypeid','商品全名',14,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1114,33,'DlyData','分布列明细','ddistdetailfield','显示字段',15,'','CheckBoxList','Height==350;',0,'',0,'订单数量★◎♂qty,订单参考金额★◎♂total,准时交货数量★◎♂toQty,准时交货参考金额★◎♂toTotal,准时交货率(%)★◎♂toRate,延时交货数量★◎♂delayQty,延时交货参考金额★◎♂delayTotal,延时交货率(%)★◎♂delayRate,终止数量★◎♂stopQty,终止参考金额★◎♂stopTotal,到货数量★◎♂completeQty,到货参考金额★◎♂completeTotal,已付金额★◎♂payMoney,未付金额★◎♂nopayMoney',0,3)

--34	销售排行榜
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1350,34,'DlyData','维度列','dlistfield','配置列',13,'','DragableCheckBoxList','Height==120;data_appendgoodstrait==true',0,'',0,'商品类别★◎♂ptypecategory,商品★◎♂ptypeid,客户★◎♂btypeid,机构★◎♂branchid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1351,34,'__NotUse__','查询方式','querymethod','查询方式',-1,'nvarchar','','',0,'',60,'商品★◎♂ptypeid,经手人★◎♂etypeid,客户★◎♂btypeid,仓库★◎♂ktypeid,供应商★◎♂btypeid1',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1352,34,'branch','分支机构','ctypeid','机构名称',1,'nvarchar','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid,etypeid;TypeName==rsCtype',0,'',60,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1353,34,'employee','雇员','etypeid','经手人',4,'nvarchar','TC','Tag==SELECTTYPE=0|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsEtype',0,'',60,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)  
VALUES(1354,34,'btype','往来单位','btypeid','客户',2,'nvarchar','TC','Tag==SELECTTYPE=30|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsBtype;',0,'',60,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1355,34,'stock','仓库','ktypeid','仓库',3,'nvarchar','TC','Tag==PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',60,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1356,34,'PriceType','售价类型','salepriceid','参考价格',6,'nchar','','',0,'',60,'必写1★◎♂0,必写2★◎♂1',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1357,34,'__NotUse__','销售类型','opid','销售类型',5,'nchar','CheckBoxList','',0,'',60,'批发★◎♂1,零售★◎♂2,加盟配货★◎♂3',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1358,34,'__NotUse__','开始日期','billdate_s','开始日期',7,'date','','',0,'',0,'',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1359,34,'__NotUse__','截止日期','billdate_e','截止日期',8,'date','','',0,'',0,'',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1310,34,'definetype','自定义类型','definetype','自定义类型   ',9,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1361,34,'definename','类型名称','definename','类型名称',10,'nvarchar','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',60,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1362,34,'__NotUse__','包含停用商品','containsstop','包含停用商品',11,'bit','','',0,'',0,'',0,2)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1363,34,'__NotUse__','商品','ptypeid','商品全名',12,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1364,34,'__NotUse__','颜色','colorid','颜色',13,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1365,34,'__NotUse__','尺码','sizeid','尺码',14,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1366,34,'DlyData','分布列明细','ddistdetailfield','显示字段',15,'','CheckBoxList','Height==350;',0,'',0,'零售价★◎♂RetailPrice,零售金额★◎♂RetailTotal,销售数量★◎♂SaleQty,折前金额★◎♂ZqTotal,销售金额★◎♂SaleTotal,参考金额★◎♂dhrefTotal,销售折扣额★◎♂SaleZqTotal,税额★◎♂TaxTotal,成本金额★◎♂CostTotal,价税合计★◎♂PriceTaxTotal,毛利额★◎♂MlTotal,销售金额比重(%)★◎♂SaleTotalBz,毛利比重(%)★◎♂MlBz,毛利率(%)★◎♂MlRate',1,3)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1367,34,'ptypecategory','商品类别','ptypecategory','商品类别',16,'nvarchar','CheckBoxList','Height==65;',0,'',60,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2)

--35	采购明细分析
   insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
   values (1420,35,'operationinfo2','退货类型','opid2','退货类型',7,'nvarchar','CheckBoxList','',0,'',60,'退货类型1★◎♂1,发货类型2★◎♂2',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1419,35,'__NotUse__','单据类型','djType','单据类型',5,'nvarchar','CheckBoxList','',0,'',60,'采购入库单★◎♂34,采购退货单★◎♂6',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1401,35,'branch','分支机构','ctypeid','机构名称',1,'nvarchar','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=ktypeid;TypeName==rmCtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1402,35,'btype','往来单位','btypeid','供应商',2,'nvarchar','TC','Tag==SELECTTYPE=1|ISQUICKQUERY=1;TypeName==rsBtype;',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1403,35,'stock','仓库','ktypeid','仓库',3,'nvarchar','TC','Tag==SELECTTYPE=7|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rmKtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1404,35,'employee','雇员','etypeid','经手人',4,'nvarchar','TC','Tag==SELECTTYPE=0|ISQUICKQUERY=1;TypeName==rsEtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1405,35,'operationinfo','交易信息','opid','收货类型',6,'nvarchar','CheckBoxList','',0,'',60,'类型1★◎♂1,类型2★◎♂2',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1406,35,'__NotUse__','红冲单据','isred','单据状态',8,'nvarchar','','',0,'',60,'全部单据★◎♂0,显示红冲单据★◎♂T,不显示红冲单据★◎♂F',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1407,35,'PriceType','售价类型','salepriceid','参考价格',8,'nchar','','',0,'',60,'必写1★◎♂0,必写2★◎♂1',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1408,35,'__NotUse__','开始日期','billdate_s','开始日期',9,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1409,35,'__NotUse__','截止日期','billdate_e','截止日期',10,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1412,35,'definetype','自定义类型','definetype','自定义类型   ',12,'nvarchar','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1413,35,'definename','类型名称','definename','类型名称',13,'nvarchar','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1414,35,'__NotUse__','包含停用商品','containsstop','包含停用商品',14,'bit','','',0,'',0,'',0,2)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1415,35,'__NotUse__','商品','ptypeid','商品全名',15,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1417,35,'DlyData','分布列明细','ddistdetailfield','显示字段',17,'','CheckBoxList','Height==350;',0,'',0,'数量★◎♂Qty,单价★◎♂Price,金额★◎♂Total,参考单价★◎♂dhrefprice,参考金额★◎♂dhreftotal,折扣（%）★◎♂Discount,折后单价★◎♂wsPrice,折后金额★◎♂wsTotal,成交金额★◎♂cjTotal,税率(%)★◎♂Tax,税额★◎♂TaxMoney,含税单价★◎♂TaxPrice,含税金额★◎♂TaxTotal,折让★◎♂DiscountTotal',0,3)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1418,35,'__NotUse__','查询方式','querymethod','查询方式',0,'char','','',0,'',60,'商品★◎♂ptypeid,经手人★◎♂etypeid,供应商★◎♂btypeid',1,1)



--36   机构盈利统计分析
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
   values (1450,36,'branch','分支机构','ctypeid','机构名称',1,'nvarchar','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=etypeid;TypeName==rmCtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1451,36,'employee','雇员','etypeid','经手人',2,'nvarchar','TC','Tag==SELECTTYPE=1|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsEtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1452,36,'__NotUse__','开始日期','billdate_s','开始日期',3,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1453,36,'__NotUse__','截止日期','billdate_e','截止日期',4,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1454,36,'__NotUse__','包含停用商品','containsstop','包含停用商品',5,'bit','','',0,'',0,'',0,2)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1455,36,'__NotUse__','商品','ptypeid','商品全名',6,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rmPtype',0,'',60,'',0,2)

--37   机构采购分布汇总统计
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
   values (1477,37,'__NotUse__','单据类型','djType','单据类型',7,'int','','',0,'',0,'全部★◎♂0,采购入库单★◎♂34,采购退货单★◎♂6',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1471,37,'branch','分支机构','ctypeid','机构名称',1,'VARCHAR','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|ISONLYLIST=1|CLEARCONTROL=ktypeid;TypeName==rmCtype',0,'',60,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1472,37,'btype','往来单位','btypeid','供应商',2,'nvarchar','TC','Tag==SELECTTYPE=1|ISQUICKQUERY=1;TypeName==rsBtype;',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1473,37,'stock','仓库','ktypeid','仓库',3,'nvarchar','TC','Tag==SELECTTYPE=7|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1474,37,'employee','雇员','etypeid','经手人',4,'nvarchar','TC','Tag==SELECTTYPE=0|ISQUICKQUERY=1;TypeName==rsEtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1476,37,'PriceType','售价类型','salepriceid','参考价格',6,'nchar','','',0,'',60,'必写1★◎♂0,必写2★◎♂1',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1478,37,'__NotUse__','开始日期','billdate_s','开始日期',8,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1479,37,'__NotUse__','截止日期','billdate_e','截止日期',9,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1480,37,'definetype','自定义类型','definetype','自定义类型   ',10,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1481,37,'definename','类型名称','definename','类型名称',11,'nvarchar','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1482,37,'__NotUse__','包含停用商品','containsstop','包含停用商品',12,'bit','','',0,'',0,'',0,2)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1483,37,'__NotUse__','商品','ptypeid','商品全名',13,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1487,37,'__NotUse__','颜色','colorid','颜色',17,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1488,37,'__NotUse__','尺码','sizeid','尺码',18,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1485,37,'DlyData','分布列明细','ddistdetailfield','显示字段',15,'','CheckBoxList','Height==350;',0,'',0,'数量★◎♂qty,金额★◎♂total',1,3)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1486,37,'ptypecategory','商品类别','ptypecategory','商品类别',16,'nvarchar','CheckBoxList','Height==65;',0,'',60,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1484,37,'DlyData','维度列','dlistfield','配置列',14,'','DragableCheckBoxList','Height==280;data_appendgoodstrait==true',0,'',0,'供应商★◎♂btypeid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)


--38   发货类型销售分析
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1513,38,'DlyData','维度列','dlistfield','配置列',13,'int','DragableCheckBoxList','Height==280;data_appendgoodstrait==true',0,'',0,'客户★◎♂btypeid,经手人★◎♂etypeid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1500,38,'__NotUse__','查询方式','querymethod','查询方式',0,'char','','',0,'',0,'商品★◎♂ptypeid,经手人★◎♂etypeid,客户★◎♂btypeid',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1501,38,'branch','分支机构','ctypeid','机构名称',1,'int','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid;TypeName==rsCtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1502,38,'btype','往来单位','btypeid','客户',2,'int','TC','Tag==SELECTTYPE=2|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsBtype;',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1503,38,'stock','仓库','ktypeid','仓库',3,'int','TC','Tag==SELECTTYPE=7|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1504,38,'employee','雇员','etypeid','经手人',4,'int','TC','Tag==SELECTTYPE=0|ISQUICKQUERY=1;TypeName==rsEtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1506,38,'PriceType','售价类型','salepriceid','参考价格',6,'char','','',0,'',0,'必写1★◎♂0,必写2★◎♂1',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1507,38,'__NotUse__','开始日期','billdate_s','开始日期',7,'date','','',0,'',0,'',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1508,38,'__NotUse__','截止日期','billdate_e','截止日期',8,'date','','',0,'',0,'',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1509,38,'definetype','自定义类型','definetype','自定义类型   ',9,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1510,38,'definename','类型名称','definename','类型名称',10,'int','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1511,38,'__NotUse__','包含停用商品','containsstop','包含停用商品',11,'bit','','',0,'',0,'',0,2)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1512,38,'__NotUse__','商品','ptypeid','商品全名',12,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsPtype',0,'',0,'',0,2)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1514,38,'DlyData','分布列明细','ddistdetailfield','显示字段',14,'int','CheckBoxList','Height==350;',0,'',0,'销售数量★◎♂qty,销售金额★◎♂total',0,3)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1515,38,'ptypecategory','商品类别','ptypecategory','商品类别',15,'int','CheckBoxList','Height==65;',0,'',0,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2)


--39   配货单明细分析
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1555,39,'branch','分支机构','ctypeid1','配货机构',5,'int','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid;TypeName==rsCtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1560,39,'operationinfo2','退货类型','opid2','退货类型',10,'int','CheckBoxList','',0,'',0,'退货类型1★◎♂1,发货类型2★◎♂2',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1561,39,'__NotUse__','单据类型','djType','单据类型',11,'int','','',0,'',0,'全部★◎♂0,同价配货单★◎♂218_1,变价配货单★◎♂212_1,同价调配单★◎♂218_3,变价调配单★◎♂212_3,同价退货单★◎♂218_2,变价退货单★◎♂212_2,加盟商配货单★◎♂222,加盟商退货单★◎♂234',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1554,39,'branch','分支机构','ctypeid','申请机构',4,'int','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid;TypeName==rsCtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1557,39,'stock','仓库','ktypeid','仓库',7,'int','TC','Tag==SELECTTYPE=7|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1558,39,'employee','雇员','etypeid','经手人',8,'int','TC','Tag==SELECTTYPE=0|ISQUICKQUERY=1;TypeName==rsEtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1559,39,'operationinfo','交易信息','opid','发货类型',9,'int','CheckBoxList','',0,'',0,'类型1★◎♂1,类型2★◎♂2',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1562,39,'PriceType','售价类型','salepriceid','参考价格',12,'char','','',0,'',0,'必写1★◎♂0,必写2★◎♂1',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1563,39,'__NotUse__','开始日期','billdate_s','开始日期',13,'date','','',0,'',0,'',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1564,39,'__NotUse__','截止日期','billdate_e','截止日期',14,'date','','',0,'',0,'',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1565,39,'definetype','自定义类型','definetype','自定义类型   ',15,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1566,39,'definename','类型名称','definename','类型名称',16,'int','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1552,39,'__NotUse__','包含停用商品','containsstop','包含停用商品',2,'bit','','',0,'',0,'',0,2)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1553,39,'__NotUse__','商品','ptypeid','商品全名',3,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsPtype',0,'',0,'',0,2)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1551,39,'DlyData','分布列明细','ddistdetailfield','显示字段',1,'int','CheckBoxList','Height==350;',0,'',0,'数量★◎♂Qty,报价★◎♂Price,金额★◎♂Total,参考单价★◎♂dhrefprice,参考金额★◎♂dhreftotal',0,3)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1550,39,'__NotUse__','查询方式','querymethod','查询方式',0,'char','','',0,'',0,'商品★◎♂ptypeid,经手人★◎♂etypeid,申请机构★◎♂branchid',1,1)


--40   采购建议表
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1602,40,'btype','往来单位','btypeid','供应商',2,'int','TC','Tag==SELECTTYPE=1|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsBtype;',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1604,40,'__NotUse__','均量基数(天)','basenum','均量基数(天)',4,'int','NumberEdit','Tag==NumberType=PositiveInt|Width=110|MinValue=0|MaxValue=99999|Required=true|ReportField=均量基数(天)',0,'',0,'7',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1605,40,'__NotUse__','销售类型','opid','销售类型',5,'int','CheckBoxList','',0,'',0,'批发★◎♂1,零售★◎♂2,加盟配货★◎♂3',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1611,40,'ptypecategory','商品类别','ptypecategory','商品类别',11,'int','CheckBoxList','Height==65;',0,'',0,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1601,40,'branch','分支机构','ctypeid','机构名称',1,'int','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=btypeid,ktypeid;TypeName==rsCtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1603,40,'stock','仓库','ktypeid','仓库',3,'int','TC','Tag==SELECTTYPE=7|PARENTCONTROL=ctypeid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1610,40,'__NotUse__','商品','ptypeid','商品全名',10,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsPtype',0,'',0,'',0,2)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1606,40,'__NotUse__','开始日期','billdate_s','开始日期',6,'date','','',0,'',0,'',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1607,40,'__NotUse__','截止日期','billdate_e','截止日期',7,'date','','',0,'',0,'',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1608,40,'definetype','自定义类型','definetype','自定义类型   ',8,'int','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1609,40,'definename','类型名称','definename','类型名称',9,'int','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',0,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1612,40,'__NotUse__','包含停用商品','containsstop','包含停用商品',12,'bit','','',0,'',0,'',0,2)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1600,40,'DlyData','分布列明细','ddistdetailfield','显示字段',0,'int','CheckBoxList','Height==350;',0,'',0,'库存余量★◎♂kcyl,最低库存量★◎♂zdkcl,采购总量★◎♂cgsl,采购补货数量★◎♂cgbhl,采购订货量★◎♂cgdhl,对照期销量★◎♂dzqxl,销售总量★◎♂xssl,均销量★◎♂jxl,销售补货数量★◎♂xsbhl,销售退货量★◎♂xsthl,销售订货量★◎♂xsdhl,配货订货量★◎♂phdhl,配货退货申请量★◎♂phthsql,建议采购量★◎♂jycgl',0,3)


--41   机构销售分布汇总统计
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1651,41,'__NotUse__','分支机构','branchmode','机构模式',1,'nvarchar','RADIOBUTTONLIST','',0,'',2,'0=内部机构,1=加盟机构',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1652,41,'branch','分支机构','branchid','机构名称',2,'VARCHAR','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=etypeid,ktypeid;TypeName==rmCtype',0,'',2000,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1653,41,'stock','仓库','ktypeid','仓库',3,'NVARCHAR','TC','Tag==SELECTTYPE=31|PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1654,41,'employee','雇员','etypeid','经手人',4,'NVARCHAR','TC','Tag==SELECTTYPE=1|PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsEtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1655,41,'__NotUse__','开始日期','billdate_s','开始日期',5,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1656,41,'__NotUse__','截止日期','billdate_e','截止日期',6,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
 VALUES (1657,41,'vchtypeid','交易信息','vchtypeid','销售类型',7,'NVARCHAR','CheckBoxList','',0,'',200,'批发★◎♂1,零售★◎♂2,加盟商配货★◎♂3',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1658,41,'operationinfo','发货类型','opid1','发货类型		',8,'NVARCHAR','CheckBoxList','',0,'',400,'类型1★◎♂1,类型2★◎♂2',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1659,41,'operationinfo2','退货类型','opid3','退货类型',9,'NVARCHAR','CheckBoxList','',0,'',400,'退货类型1★◎♂1,发货类型2★◎♂2',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1660,41,'definetype','自定义类型','definetype','自定义类型',10,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',200,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1661,41,'definename','类型名称','definename','类型名称',11,'NVARCHAR','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',200,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1662,41,'__NotUse__','包含停用商品','containsstop','包含停用商品',12,'bit','','',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1663,41,'__NotUse__','商品','ptypeid','商品全名',13,'NVARCHAR','TC','Tag==ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1664,41,'ptypecategory','商品类别','ptypecategory','商品类别',14,'NVARCHAR','CheckBoxList','Height==65;',0,'',60,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1665,41,'__NotUse__','颜色','colorid','颜色',15,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1666,41,'__NotUse__','尺码','sizeid','尺码',16,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1667,41,'DlyData','维度列','dlistfield','配置列',17,'NVARCHAR','DragableCheckBoxList','Height==300;data_appendgoodstrait==true',0,'',400,'客户★◎♂btypeid,经手人★◎♂etypeid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1668,41,'DlyData','分布列明细','ddistdetailfield','显示字段',18,'NVARCHAR','CheckBoxList','Height==350;',0,'',400,'数量★◎♂qty,价税合计★◎♂total',1,3)

--42   商品进销存分析
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1694,42,'__NotUse__','分支机构','branchmode','机构模式',1,'nvarchar','RADIOBUTTONLIST','',0,'',2,'0=内部机构,1=加盟机构',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1681,42,'branch','分支机构','branchid','机构名称',1,'nvarchar','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1|CLEARCONTROL=ktypeid;TypeName==rsCtype',0,'',50,'',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1682,42,'stock','仓库','ktypeid','仓库',2,'nvarchar','TC','Tag==PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',50,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1692,42,'btype','往来单位','btypeid','主供应商',3,'nvarchar','TC','Tag==SELECTTYPE=1|ISQUICKQUERY=1;TypeName==rsBtype;',0,'',50,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1683,42,'PriceType','售价类型','salepriceid','参考价格',4,'nchar','','',0,'',60,'必写1★◎♂0,必写2★◎♂1',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1684,42,'__NotUse__','录单开始日期','billdate_s','录单开始日期',5,'date','','',0,'',0,'',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1685,42,'__NotUse__','录单截止日期','billdate_e','录单截止日期',6,'date','','',0,'',0,'',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1693,42,'__NotUse__','包含停用商品','containsstop','包含停用商品',9,'bit','','',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
VALUES(1686,42,'__NotUse__','商品','ptypeid','商品全名',10,'nvarchar','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
VALUES(1687,42,'ptypecategory','商品类别','ptypecategory','商品类别',11,'nvarchar','CheckBoxList','Height==65;',0,'',100,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1688,42,'__NotUse__','颜色','colorid','颜色',12,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1689,42,'__NotUse__','尺码','sizeid','尺码',13,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1690,42,'__NotUse__','维度列','dlistfield','配置列',15,'','DragableCheckBoxList','Height==280;data_appendgoodstrait==true;enabled==ptypeid',0,'',0,'主供应商★◎♂btypeid,机构★◎♂branchid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1691,42,'__NotUse__','分布列明细','ddistdetailfield','显示字段',16,'','CheckBoxList','Height==350;',0,'',0,'数量★◎♂qty,参考金额★◎♂total',0,3)

--43   库龄分析
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1711,43,'branch','分支机构','branchid','机构名称',1,'nvarchar','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=ktypeid;TypeName==rsCtype',0,'',60,'',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1712,43,'stock','仓库','ktypeid','仓库',2,'nvarchar','TC','Tag==PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==vsKtype',0,'',60,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
VALUES(1713,43,'__NotUse__','商品','ptypeid','商品全名          ',3,'nvarchar','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1714,43,'__NotUse__','包含停用商品','containsstop','包含停用商品',4,'bit','','',0,'',0,'',0,2)



--44   销售成本分析
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES(1741,44,'branch','分支机构','branchid','机构名称',1,'NVARCHAR','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1;TypeName==rsCtype',0,'',60,'',0,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES(1742,44,'stock','仓库','ktypeid','仓库',2,'nvarchar','TC','Tag==PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',50,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES(1743,44,'btype','客户','Btypeid','客户',3,'nvarchar','TC','Tag==SELECTTYPE=2|ISQUICKQUERY=1;TypeName==rsBtype',0,'',60,'',0,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES(1744,44,'employee','雇员','etypeid','经手人',4,'nvarchar','TC','Tag==SELECTTYPE=0|ISQUICKQUERY=1;TypeName==rsEtype',0,'',60,'',0,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES(1745,44,'__NotUse__','商品','ptypeid','商品全名',5,'nvarchar','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES(1746,44,'__NotUse__','开始日期','billdate_s','开始日期',6,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES(1747,44,'__NotUse__','截止日期','billdate_e','截止日期',7,'date','','',0,'',0,'',1,1) 
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES(1748,44,'__NotUse__','包含停用商品','containsstop','包含停用商品',8,'bit','','',0,'',0,'',0,2)

--45	POS销存动态跟踪
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1771,45,'size','机构名称','DistributingKeys','尺码分布组',1,'VARCHAR','TC','Tag==SELECTTYPE=-1|ISQUICKQUERY=1;TypeName==rmWtype',0,'',200,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1772,45,'branch','机构名称','branchid','机构名称',2,'NVARCHAR','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1;TypeName==rsCtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1773,45,'__NotUse__','查询日期','billdate_e','查询日期   ',3,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1774,45,'__NotUse__','商品全名','ptypeid','商品全名',4,'NVARCHAR','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2)
 
--46	商品畅滞销分析
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES(1801,46,'__NotUse__','分支机构','branchmode','机构模式',1,'nvarchar','RADIOBUTTONLIST','',0,'',2,'0=内部机构,1=加盟机构',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES(1802,46,'branch','分支机构','branchid','机构名称',2,'NVARCHAR','TC','Tag==SELECTTYPE=15|ISQUICKQUERY=1;TypeName==rsCtype',0,'',60,'',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES(1803,46,'stock','仓库','ktypeid','仓库',3,'nvarchar','TC','Tag==PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsKtype',0,'',50,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES(1804,46,'vchtypeid','交易信息','vchtypeid','销售类型',4,'NVARCHAR','CheckBoxList','',0,'',200,'批发★◎♂1,零售★◎♂2,加盟商配货★◎♂3',60,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES(1805,46,'__NotUse__','计算销售百分比基数','percentmode','销售百分比基数',5,'nvarchar','RADIOBUTTONLIST','',0,'',2,'1=本期入库数,2=本期进货数,3=本期库存,4=上期库存+本期入库,5=上期库存+本期进货',60,1)
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES(1806,46,'__NotUse__','上市日期','goodsdate_s','上市日期起始',6,'date','','',0,'',0,'',1,1) 
 INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES(1807,46,'__NotUse__','过季日期','goodsdate_e','上市日期截止',7,'date','','',0,'',0,'',1,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
    VALUES(1808,46,'__NotUse__','开始日期','billdate_s','开始日期',8,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
    VALUES(1809,46,'__NotUse__','截止日期','billdate_e','截止日期',9,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
	VALUES(1810,46,'salepercent','销售比例大于()%','salepercent1','销售比例>=(%)',10,'nchar','','',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
    VALUES(1811,46,'salepercent','销售比例小于()%','salepercent2','销售比例<=(%)',11,'nchar','','',0,'',0,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
    VALUES(1812,46,'salepercent','显示排行前{}位','topn','显示排行前()位',12,'int','','',0,'',0,'',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES(1813,46,'__NotUse__','包含停用商品','containsstop','包含停用商品',13,'bit','','',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES(1814,46,'__NotUse__','商品','ptypeid','商品全名',14,'nvarchar','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES(1815,46,'ptypecategory','商品类别','ptypecategory','商品类别',15,'nvarchar','CheckBoxList','Height==65;',0,'',100,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES(1816,46,'__NotUse__','颜色','colorid','颜色',16,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',0,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES(1817,46,'__NotUse__','尺码','sizeid','尺码',17,'int','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',0,'',0,2)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
	VALUES(1818,46,'__NotUse__','维度列','dlistfield','配置列',18,'','DragableCheckBoxList','Height==280;data_appendgoodstrait==true',0,'',0,'商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)


--47	机构促销分析
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
	VALUES (1831,47,'branch','机构名称','branchid','机构名称',1,'nvarchar','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1;TypeName==rsCtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel )
	VALUES (1832,47,'__NotUse__','开始日期','billdate_s','开始日期',8,'date','','',0,'',0,'',1,1) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
	VALUES (1833,47,'__NotUse__','截止日期','billdate_e','截止日期',9,'date','','',0,'',0,'',1,1) 

--48	商品零售分析
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1850,48,'branch','分支机构','ctypeid','机构名称',1,'nvarchar','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1;TypeName==rmCtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1851,48,'__NotUse__','开始日期','billdate_s','开始日期',2,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1852,48,'__NotUse__','截止日期','billdate_e','截止日期',3,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1853,48,'PriceType','售价类型','salepriceid','参考价格',4,'nchar','','',0,'',60,'必写1★◎♂0,必写2★◎♂1',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1854,48,'definetype','自定义类型','definetype','自定义类型   ',5,'nvarchar','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1855,48,'definename','类型名称','definename','类型名称',6,'nvarchar','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1862,48,'__NotUse__','包含停用商品','containsstop','包含停用商品',7,'bit','','',0,'',0,'',0,2)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1856,48,'__NotUse__','商品','ptypeid','商品全名',8,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
VALUES(1857,48,'ptypecategory','商品类别','ptypecategory','商品类别',9,'nvarchar','CheckBoxList','Height==65;',0,'',100,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1858,48,'__NotUse__','颜色','colorid','颜色',10,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',60,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1859,48,'__NotUse__','尺码','sizeid','尺码',10,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',60,'',0,2)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1860,48,'DlyData','维度列','dlistfield','配置列',11,'','DragableCheckBoxList','Height==120;data_appendgoodstrait==true',0,'',0,'机构★◎♂branchid,经手人★◎♂etypeid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1861,48,'DlyData','分布列明细','ddistdetailfield','显示字段',12,'','CheckBoxList','Height==350;',0,'',0,'零售销售数量★◎♂saleqty,零售销售参考金额★◎♂saletotal,零售退货数量★◎♂backqty,零售退货参考金额★◎♂backtotal,实际销售数量★◎♂qty,实际销售参考金额★◎♂total,平均折扣%★◎♂discount,平均单价★◎♂price,价税合计★◎♂tax_total,抽成额★◎♂deducttotal,税额★◎♂taxtotal,毛利额★◎♂profittotal,毛利额占比%★◎♂profitrate',1,3)


--49	赠品分析
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1900,49,'branch','分支机构','ctypeid','机构名称',1,'nvarchar','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1;TypeName==rmCtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1901,49,'__NotUse__','开始日期','billdate_s','开始日期',2,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1902,49,'__NotUse__','截止日期','billdate_e','截止日期',3,'date','','',0,'',0,'',1,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1903,49,'PriceType','售价类型','salepriceid','参考价格',4,'nchar','','',0,'',60,'必写1★◎♂0,必写2★◎♂1',1,1)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
VALUES(1904,49,'__NotUse__','销售类型','saletype','销售方式',5,'nchar','CheckBoxList','',0,'',60,'批发★◎♂1,零售★◎♂2,加盟配货★◎♂3,赠送单★◎♂4',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1905,49,'definetype','自定义类型','definetype','自定义类型',6,'nvarchar','TC','Tag==SELECTTYPE=7|ISQUICKQUERY=1|CLEARCONTROL=definename;TypeName==rsOtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1906,49,'definename','类型名称','definename','类型名称',7,'nvarchar','TC','Tag==SELECTTYPE=5|PARENTCONTROL=definetype|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsOtype',0,'',60,'',0,1)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1907,49,'__NotUse__','包含停用商品','containsstop','包含停用商品',8,'bit','','',0,'',0,'',0,2)
insert into queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel) 
values (1908,49,'__NotUse__','商品','ptypeid','商品全名',9,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsPtype',0,'',60,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel ) 
VALUES(1912,49,'ptypecategory','商品类别','ptypecategory','商品类别',10,'nvarchar','CheckBoxList','Height==65;',0,'',100,'1★◎♂1,2★◎♂2,3★◎♂3,4★◎♂4,5★◎♂5,6★◎♂6,7★◎♂7,8★◎♂8,9★◎♂9',0,2) 
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1909,49,'__NotUse__','颜色','colorid','颜色',11,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsNtype',0,'',60,'',0,2)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,[Datalength],BaseData,ValueRequired,WhichPanel)
VALUES(1910,49,'__NotUse__','尺码','sizeid','尺码',12,'nvarchar','TC','Tag==ISQUICKQUERY=1;TypeName==rsWtype',0,'',60,'',0,2)
INSERT INTO queryfield(QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)   
VALUES(1911,49,'DlyData','维度列','dlistfield','配置列',13,'','DragableCheckBoxList','Height==300;data_appendgoodstrait==true',0,'',0,'机构★◎♂branchid,商品类别★◎♂ptypecategory,商品★◎♂ptypeid,颜色★◎♂colorid,尺码★◎♂sizeid',1,3)

--50 机构收款统计
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1950,50,'__NotUse__','开始日期','billdate_s','开始日期',1,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1951,50,'__NotUse__','截止日期','billdate_e','截止日期',2,'date','','',0,'',0,'',1,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1952,50,'Branch','机构','branchid','机构名称',3,'NVARCHAR','TC','Tag==SELECTTYPE=31|ISQUICKQUERY=1|CLEARCONTROL=etypeid;TypeName==rsCtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1953,50,'Employee','职员','etypeid','经手人',4,'NVARCHAR','TC','Tag==SELECTTYPE=0|PARENTCONTROL=branchid|ISMUSTPARENT=1|ISQUICKQUERY=1;TypeName==rsEtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1954,50,'Employee','职员','etypeid2','制单人',5,'NVARCHAR','TC','Tag==SELECTTYPE=1|ISQUICKQUERY=1;TypeName==rsEtype',0,'',60,'',0,1)
INSERT INTO dbo.QueryField (QueryFieldId,QueryModuleId,TableName,TableViewName,FieldName,FieldViewName,OrderNo,DataType,ControlType,ControlParam,IsPrimaryKey,MultiValueMode,Datalength,BaseData,ValueRequired,WhichPanel)
 VALUES (1955,50,'bakdlyorder','显示字段','ddistdetailfield','显示字段',5,'NVARCHAR','CheckBoxList','Height==65;',0,'',200,'销售总额★◎♂alltotal,零售收款-现金★◎♂retatotal_cash,零售收款-银行★◎♂retatotal_bank,零售收款-代金劵★◎♂retatotal_book,零售收款-储值卡★◎♂retatotal_card,销售收款-现金★◎♂saletotal_cash,销售收款-银行★◎♂saletotal_bank,销售收款-储值卡★◎♂saletotal_card,加盟收款-现金★◎♂jointotal_cash,加盟收款-银行★◎♂jointotal_bank,销售类型收款合计-现金★◎♂saletypetotal_cash,销售类型收款合计-银行★◎♂saletypetotal_bank,销售类型收款合计-代金劵★◎♂saletypetotal_book,销售类型收款合计-储值卡★◎♂saletypetotal_card,收款单收款-现金★◎♂formtotal_cash,收款单收款-银行★◎♂formtotal_bank,VIP充值收款-现金★◎♂viptotal_cash,VIP充值收款-银行★◎♂viptotal_bank,收款合计-现金★◎♂salealltotal_cash,收款合计-银行★◎♂salealltotal_bank,收款合计-代金劵★◎♂salealltotal_book,收款合计-储值卡★◎♂salealltotal_card',0,3)


/*
	--备注:每张报表 预留30个QueryFieldId编号,ID超出部分以底部"目前超出QueryFieldID"-1  进行编号，
	--     并更改"目前超出QueryFieldID"
*/
--- ----------------------------------------------------------------------目前超出QueryFieldID是 999999

GO


IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZSaleYMD]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZSaleYMD]
GO




CREATE PROCEDURE FZSaleYMD
    (
      @szPtypeId VARCHAR(50),
      @szKtypeid VARCHAR(50),
      @szBtypeid VARCHAR(50),
      @BeginDate VARCHAR(10),
      @EndDate VARCHAR(10),
      @type VARCHAR(1),
      @ifstop VARCHAR(2),
      @attrib1 INT = -1,
      @attrib2 INT = -1,
      @attrib3 INT = -1,
      @attrib4 INT = -1,
      @Assist1TypeID INT = -1,
      @Assist2TypeID INT = -1,
      @Assist3TypeID INT = -1,
      @Assist4TypeID INT = -1,
      @SaleTraitname VARCHAR(1000),
      @Etypeid VARCHAR(50),
      @deptid VARCHAR(50),
      @branchid VARCHAR(50),
      @OperatorId VARCHAR(50)
    )
AS /*
alter by hww 2011年9月13日16:47:35
CS中，能够通过辅助属性进行过滤
*/  

    declare @btypeidlist varchar(30)
    if EXISTS(SELECT SubValue FROM sysdata WHERE SubName = 'ProcTypeName' AND Subvalue='FZCS') 
     set @btypeidlist = '1,2,3,4,6,7'
    else
      set @btypeidlist = '2,3,4,6'

    DECLARE @OperatorIsJM BIT
    SELECT  @OperatorIsJM = SelfHelp
    FROM    Branch a
            LEFT JOIN Employee b ON a.branchid = b.branchid
    WHERE   b.typeid = @OperatorId
  
    IF @SaleTraitName = '全部' 
        SET @SaleTraitName = ''   
    IF @branchid IS NULL 
        SET @branchid = ''  
    IF @szPtypeId IS NULL
        OR @szPtypeId = '' 
        SELECT  @szPtypeId = '%'  

--总部和加盟商共用一个，当不进行筛选单据的情况下，要把单据范围补齐  
    DECLARE @vchtype VARCHAR(100)
    IF LEFT(@branchid, 5) = '00001'
        OR @branchid = '' 
        BEGIN   
            SET @vchtype = '100,11,45,24,12,222,224,4,66' --总部统计的销售主体单据  
        END  
    ELSE 
        BEGIN   
            SET @vchtype = '11,12,45,24,4,66'   --加盟商统计的销售主体单据  
        END  

    SELECT  p1.[typeid]
    INTO    #temp_p
    FROM    FN_GetPowerRangePList(@OperatorId, @szPtypeId) p1 --ptype p1  
            LEFT JOIN ( SELECT  a.ptypeid,
                                a.attributeid,
                                b.typeid
                        FROM    ptypeattribute a,
                                assistattribute b
                        WHERE   a.attributeid = b.attributeid
                                AND typeid = @Assist1TypeID
                      ) ls1 ON @attrib1 <> -1
                               AND ls1.ptypeid = p1.typeid
            LEFT JOIN ( SELECT  a.ptypeid,
                                a.attributeid,
                                b.typeid
                        FROM    ptypeattribute a,
                                assistattribute b
                        WHERE   a.attributeid = b.attributeid
                                AND typeid = @Assist2TypeID
                      ) ls2 ON @attrib2 <> -1
                               AND ls2.ptypeid = p1.typeid
            LEFT JOIN ( SELECT  a.ptypeid,
                                a.attributeid,
                                b.typeid
                        FROM    ptypeattribute a,
                                assistattribute b
                        WHERE   a.attributeid = b.attributeid
                                AND typeid = @Assist3TypeID
                      ) ls3 ON @attrib3 <> -1
                               AND ls3.ptypeid = p1.typeid
            LEFT JOIN ( SELECT  a.ptypeid,
                                a.attributeid,
                                b.typeid
                        FROM    ptypeattribute a,
                                assistattribute b
                        WHERE   a.attributeid = b.attributeid
                                AND typeid = @Assist4TypeID
                      ) ls4 ON @attrib4 <> -1
                               AND ls4.ptypeid = p1.typeid
    WHERE   deleted = 0
            AND stop = CASE @ifstop
                         WHEN '0' THEN '0'
                         ELSE stop
                       END
            AND ( ( parid LIKE @szPtypeId + '%'
                    AND sonnum = 0
                  )
                  OR ( p1.typeid = @szPtypeid
                       AND sonnum = 0
                     )
                )
            AND ISNULL(ls1.attributeid, -1) = CASE WHEN @attrib1 = -1
                                                   THEN ISNULL(ls1.attributeid, -1)
                                                   ELSE @attrib1
                                              END
            AND ISNULL(ls2.attributeid, -1) = CASE WHEN @attrib2 = -1
                                                   THEN ISNULL(ls2.attributeid, -1)
                                                   ELSE @attrib2
                                              END
            AND ISNULL(ls3.attributeid, -1) = CASE WHEN @attrib3 = -1
                                                   THEN ISNULL(ls3.attributeid, -1)
                                                   ELSE @attrib3
                                              END
            AND ISNULL(ls4.attributeid, -1) = CASE WHEN @attrib4 = -1
                                                   THEN ISNULL(ls4.attributeid, -1)
                                                   ELSE @attrib4
                                              END  
       SELECT TypeId INTO #SaleYMD_B FROM FN_GetPowerRangeBList(@OperatorId, @szBtypeid, '1,2,3,4,6,7') FilterB 
       UNION SELECT ''
       SELECT TypeId INTO #SaleYMD_B1 FROM FN_GetPowerRangeBList(@OperatorId, @szBtypeid, @btypeidlist) FilterB
       UNION SELECT ''
       SELECT TypeId INTO #SaleYMD_E FROM FN_GetPowerRangeEList(@OperatorId, @EtypeID) FilterE
       UNION SELECT ''
       SELECT KTypeId INTO #SaleYMD_K  FROM FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) FilterK
       UNION SELECT ''
       SELECT BranchId INTO #SaleYMD_BC FROM FN_GetPowerRangeBCList(@OperatorID,'') FilterBC 
			WHERE EXISTS ( SELECT 1 FROM   Branch bc WHERE  bc.BranchId = FilterBC.Branchid AND bc.selfHelp = @OperatorIsJM )
       SELECT BranchId INTO #SaleYMD_BC1 FROM FN_GetPowerRangeBCList(@OperatorID,@BranchId) FilterBC
			WHERE EXISTS ( SELECT 1 FROM   Branch bc WHERE  bc.BranchId = FilterBC.Branchid AND bc.selfHelp = @OperatorIsJM )
	  SELECT GetID into #SaleYMD_VCH FROM   FN_GetIdStrListTable(@vchtype) FilterVch
       
       CREATE CLUSTERED INDEX I_SaleYMD_B_typeid ON #SaleYMD_B(TypeId)
       CREATE CLUSTERED INDEX I_SaleYMD_B1_typeid ON #SaleYMD_B1(TypeId)
       CREATE CLUSTERED INDEX I_SaleYMD_E_typeid ON #SaleYMD_E(TypeId)
       CREATE CLUSTERED INDEX I_SaleYMD_K_typeid ON #SaleYMD_K(KTypeId)
       CREATE CLUSTERED INDEX I_SaleYMD_BC_typeid ON #SaleYMD_BC(BranchId)
       CREATE CLUSTERED INDEX I_SaleYMD_BC1_typeid ON #SaleYMD_BC1(BranchId)
       CREATE CLUSTERED INDEX I_SaleYMD_VCH_typeid ON #SaleYMD_VCH(GetID)
       
    IF @type = 'Y' --按年统计  
        BEGIN  
			SELECT  SUBSTRING([date], 1, 4) AS [date],
                                        SUM(ISNULL(-s.[qty], 0)) AS [Qty],
                                        SUM(ISNULL(-s.[BargainTotal], 0)) AS Total,
                                        SUM(ISNULL(-s.CostTotal, 0)) AS CostTotal,
                                        SUM(ISNULL(-s.[BargainTotal], 0))
                                        - SUM(ISNULL(-s.CostTotal, 0)) AS Profittotal INTO #SaleYMD_dd
                                FROM    Dlydata s 
										inner join #SaleYMD_B FilterB ON s.BtypeId = FilterB.TypeId
										INNER JOIN #SaleYMD_E FilterE ON s.EtypeId = FilterE.TypeId
										inner join #SaleYMD_K FilterK on s.ktypeId = Filterk.KtypeId
										inner join #SaleYMD_BC1 FilterBC on s.Branchid = FilterBC.branchid
										inner join #SaleYMD_VCH FilterVch ON s.VchType = FilterVch.GetID
                                WHERE   s.billtype = 2
                                        AND s.redold = 'F'
                                        AND usedtype = CASE WHEN vchtype IN ( 222, 224 )
                                                            THEN 1
                                                            ELSE usedtype
                                                       END
	                                --AND s.BranchId LIKE @BranchId + '%'
	                                /*AND EXISTS ( SELECT GetID
	                                             FROM   FN_GetIdStrListTable(@vchtype) FilterVch
	                                             WHERE  s.VchType = FilterVch.GetID )  --单据类型  
                                        
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B FilterB
	                                             WHERE  s.BtypeId = FilterB.TypeId 
	                                          )
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  s.EtypeId = FilterE.TypeId )
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_K FilterK
	                                             WHERE  s.ktypeId = Filterk.KtypeId )
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC FilterBC
	                                             WHERE  s.Branchid = FilterBC.branchid )*/
                                GROUP BY SUBSTRING([date], 1, 4)
            SELECT DISTINCT
                    c.[date],
                    ds.qty,
                    ds.TOtal,
                    ds.costTotal,
                    ds.profittotal,
                    ISNULL(da.arTotal, 0) - ISNULL(db.apTotal, 0) AS arTotal,
                    ISNULL(back.HKTotal, 0) AS BackTotal
            FROM    ( SELECT  DISTINCT  SUBSTRING([date], 1, 4) AS [date]
                      FROM      dlyndx
                      WHERE     draft = 2
                                AND redold = 'F'
--                                 AND EXISTS ( SELECT GetID
--                                              FROM   FN_GetIdStrListTable(@vchtype) FilterVch
--                                              WHERE  dlyndx.VchType = FilterVch.GetID )  --单据类型  		   		   
--                                 AND
--                                 ( EXISTS ( SELECT 1
--                                              FROM   FN_GetPowerRangeBList(@OperatorId, @szBtypeid, '1,2,3,4,6,7') FilterB
--                                              WHERE  dlyndx.BtypeId = FilterB.TypeId )
--                                              OR dlyndx.BtypeId=''  	
--                                 )
--                                 AND
--                                 ( EXISTS ( SELECT 1
--                                              FROM   FN_GetPowerRangeEList(@OperatorId, @EtypeID) FilterE
--                                              WHERE  dlyndx.EtypeId = FilterE.TypeId )
--                                              OR dlyndx.EtypeId=''  	
--                                 )
--                                 AND
--                                 ( EXISTS ( SELECT 1
--                                              FROM   FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) FilterK
--                                              WHERE  dlyndx.ktypeId = Filterk.KtypeId OR dlyndx.ktypeId2 = Filterk.KtypeId )
--                                              OR dlyndx.KtypeId=''  	--收款单 仓库为空
--                                 )
--                                 AND  EXISTS ( SELECT 1
--                                              FROM   FN_GetPowerRangeBCList(@OperatorID, @BranchId) FilterBC
--                                              WHERE  dlyndx.Branchid = FilterBC.branchid OR dlyndx.Branchid2 = FilterBC.branchid )
                                AND SUBSTRING([date], 1, 4) BETWEEN @BeginDate AND @EndDate
                    ) C
                    LEFT JOIN #SaleYMD_dd ds ON ds.date = c.date
                    LEFT JOIN ( SELECT  SUBSTRING([date], 1, 4) AS [date],
                                        SUM(a.Total) AS ArTotal
                                FROM    dlya a
										inner  join #SaleYMD_B1 FilterB ON a.BtypeId = FilterB.TypeId
										INNER  JOIN #SaleYMD_E FilterE ON a.EtypeId = FilterE.TypeId
										inner  join #SaleYMD_BC1 FilterBC on a.Branchid = FilterBC.branchid
                                WHERE   a.atypeid = '0000100005'
                                        AND redold = 'F'
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 ) 
	                                /*AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )*/
                                GROUP BY SUBSTRING([date], 1, 4)
                              ) da ON c.[date] = da.[date]
                    LEFT JOIN ( SELECT  SUBSTRING([date], 1, 4) AS [date],
                                        SUM(a.Total) AS ApTotal
                                FROM    dlya a
										inner  join #SaleYMD_B1 FilterB ON a.BtypeId = FilterB.TypeId
										INNER  JOIN #SaleYMD_E FilterE ON a.EtypeId = FilterE.TypeId
										inner  join #SaleYMD_BC1 FilterBC on a.Branchid = FilterBC.branchid
                                WHERE   a.atypeid = '0000200001'
                                        AND redold = 'F'
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 ) --单据类型
	                                /*AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )*/
                                GROUP BY SUBSTRING([date], 1, 4)
                              ) db ON c.[date] = db.[date]
                    LEFT JOIN ( SELECT  SUBSTRING([date], 1, 4) AS [date],
                                        SUM(CASE a.atypeid
                                              WHEN '0000299999' THEN -a.Total
                                              ELSE a.total
                                            END) AS HKTotal
                                FROM    dlya a
										inner  join #SaleYMD_B1 FilterB ON a.BtypeId = FilterB.TypeId
										INNER  JOIN #SaleYMD_E FilterE ON a.EtypeId = FilterE.TypeId
										inner  join #SaleYMD_BC1 FilterBC on a.Branchid = FilterBC.branchid
                                WHERE   ( LEFT(a.atypeid, 10) IN (
                                          '0000100003', '0000100004' )
                                          OR a.atypeid = '000040000300006'
                                          OR a.atypeid = '0000299999'
                                        )
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND redold = 'F'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 )--单据类型 
	                                /*AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )*/
                                GROUP BY SUBSTRING([date], 1, 4)
                              ) back ON c.[date] = back.[date]  
            RETURN 0
        END  
    IF @type = 'M' --按月统计  
        BEGIN  
            SELECT DISTINCT
                    c.[date],
                    ds.qty,
                    ds.TOtal,
                    ds.costTotal,
                    ds.profittotal,
                    ISNULL(da.arTotal, 0) - ISNULL(db.apTotal, 0) AS arTotal,
                    ISNULL(back.HKTotal, 0) AS BackTotal
            FROM    ( SELECT DISTINCT   SUBSTRING([date], 1, 7) AS [date]
                      FROM      dlyndx
                      WHERE     draft = 2
                                AND redold = 'F'
                                AND EXISTS ( SELECT GetID
                                             FROM   FN_GetIdStrListTable(@vchtype) FilterVch
                                             WHERE  dlyndx.VchType = FilterVch.GetID )  --单据类型  		   		   
                                AND
                                ( EXISTS ( SELECT 1
                                             FROM   #SaleYMD_B FilterB
                                             WHERE  dlyndx.BtypeId = FilterB.TypeId )
                                             OR dlyndx.BtypeId=''  	
                                )
                                AND
                                ( EXISTS ( SELECT 1
                                             FROM   #SaleYMD_E FilterE
                                             WHERE  dlyndx.EtypeId = FilterE.TypeId )
                                             OR dlyndx.EtypeId=''  	
                                )
                                AND
                                ( EXISTS ( SELECT 1
                                             FROM   #SaleYMD_K FilterK
                                             WHERE  dlyndx.ktypeId = Filterk.KtypeId OR dlyndx.ktypeId2 = Filterk.KtypeId )
                                             OR dlyndx.KtypeId=''  	--收款单 仓库为空
                                )
                                AND  EXISTS ( SELECT 1
                                             FROM   #SaleYMD_BC1 FilterBC
                                             WHERE  dlyndx.Branchid = FilterBC.branchid OR dlyndx.Branchid2 = FilterBC.branchid )
                                AND SUBSTRING([date], 1, 7) BETWEEN @BeginDate AND @EndDate
                    ) C
                    LEFT JOIN ( SELECT  SUBSTRING([date], 1, 7) AS [date],
                                        SUM(ISNULL(-s.[qty], 0)) AS [Qty],
                                        SUM(ISNULL(-s.[BargainTotal], 0)) AS Total,
                                        SUM(ISNULL(-s.CostTotal, 0)) AS CostTotal,
                                        SUM(ISNULL(-s.[BargainTotal], 0))
                                        - SUM(ISNULL(-s.CostTotal, 0)) AS Profittotal,
                                        SUM(CASE WHEN vchtype IN ( 100, 101 )
                                                 THEN -( BargainTotal )
                                                 ELSE 0
                                            END) AS zgccTotal
                                FROM    Dlydata S
                                WHERE   SUBSTRING([date], 1, 7) BETWEEN @BeginDate AND @EndDate
                                        AND usedtype = CASE WHEN vchtype IN ( 222, 224 )
                                                            THEN 1
                                                            ELSE usedtype
                                                       END
                                        AND s.billtype = 2
                                        AND s.redold = 'F'
	                                AND s.BranchId LIKE @BranchId + '%'
	                                AND EXISTS ( SELECT GetID
	                                             FROM   FN_GetIdStrListTable(@vchtype) FilterVch
	                                             WHERE  s.VchType = FilterVch.GetID )  --单据类型  
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B FilterB
	                                             WHERE  s.BtypeId = FilterB.TypeId )
	                                             OR s.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  s.EtypeId = FilterE.TypeId )
	                                             OR s.EtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_K FilterK
	                                             WHERE  s.ktypeId = Filterk.KtypeId )
	                                             OR s.KtypeId=''  	--收款单 仓库为空
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC FilterBC
	                                             WHERE  s.Branchid = FilterBC.branchid )
                                GROUP BY SUBSTRING([date], 1, 7)
                              ) ds ON ds.[date] = c.[date]
                    LEFT JOIN ( SELECT  SUBSTRING([date], 1, 7) AS [date],
                                        SUM(a.Total) AS ArTotal
                                FROM    dlya a
                                WHERE   a.atypeid = '0000100005'
                                        AND redold = 'F'
                                        AND SUBSTRING([date], 1, 7) BETWEEN @BeginDate AND @EndDate
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 ) --单据类型
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )
                                GROUP BY SUBSTRING([date], 1, 7)
                              ) da ON c.[date] = da.[date]
                    LEFT JOIN ( SELECT  SUBSTRING([date], 1, 7) AS [date],
                                        SUM(a.Total) AS ApTotal
                                FROM    dlya a
                                WHERE   a.atypeid = '0000200001'
                                        AND redold = 'F'
                                        AND SUBSTRING([date], 1, 7) BETWEEN @BeginDate AND @EndDate
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66) --单据类型 
                                     AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )
                                GROUP BY SUBSTRING([date], 1, 7)
                              ) db ON c.[date] = db.[date]
                    LEFT JOIN ( SELECT  SUBSTRING([date], 1, 7) AS [date],
                                        SUM(CASE a.atypeid
                                              WHEN '0000299999' THEN -a.Total
                                              ELSE a.total
                                            END) AS HKTotal
                                FROM    dlya a
                                WHERE   ( LEFT(a.atypeid, 10) IN (
                                          '0000100003', '0000100004' )
                                          OR a.atypeid = '000040000300006'
                                          OR a.atypeid = '0000299999'
                                        )
                                        AND SUBSTRING([date], 1, 7) BETWEEN @BeginDate AND @EndDate
                                        AND redold = 'F'
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 ) --单据类型  	
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )
                                GROUP BY SUBSTRING([date], 1, 7)
                              ) back ON c.[date] = back.[date]  
 
            RETURN 0
        END  
    IF @type = 'D' --按日统计  
        BEGIN  
            SELECT DISTINCT
                    c.[date],
                    ds.qty,
                    ds.TOtal,
                    ds.costTotal,
                    ds.profittotal,
                    ISNULL(da.arTotal, 0) - ISNULL(db.apTotal, 0) AS arTotal,
                    ISNULL(back.HKTotal, 0) AS BackTotal
            FROM    ( SELECT  DISTINCT  [date]
                      FROM      dlyndx
                      WHERE     draft = 2
                                AND redold = 'F'
                                AND EXISTS ( SELECT GetID
                                             FROM   FN_GetIdStrListTable(@vchtype) FilterVch
                                             WHERE  dlyndx.VchType = FilterVch.GetID )  --单据类型  		   		   
                                AND
                                ( EXISTS ( SELECT 1
                                             FROM   #SaleYMD_B FilterB
                                             WHERE  dlyndx.BtypeId = FilterB.TypeId )
                                             OR dlyndx.BtypeId=''  	
                                )
                                AND
                                ( EXISTS ( SELECT 1
                                             FROM   #SaleYMD_E FilterE
                                             WHERE  dlyndx.EtypeId = FilterE.TypeId )
                                             OR dlyndx.EtypeId=''  	
                                )
                                AND
                                ( EXISTS ( SELECT 1
                                             FROM   #SaleYMD_K FilterK
                                             WHERE  dlyndx.ktypeId = Filterk.KtypeId OR dlyndx.ktypeId2 = Filterk.KtypeId )
                                             OR dlyndx.KtypeId=''  	--收款单 仓库为空
                                )
                                AND  EXISTS ( SELECT 1
                                             FROM   #SaleYMD_BC1 FilterBC
                                             WHERE  dlyndx.Branchid = FilterBC.branchid OR dlyndx.Branchid2 = FilterBC.branchid )
                                AND [date] BETWEEN @BeginDate AND @EndDate
                    ) C
                    LEFT JOIN ( SELECT  [date],
                                        SUM(ISNULL(-ss.[qty], 0)) AS [Qty],
                                        SUM(ISNULL(-ss.[BargainTotal], 0)) AS Total,
                                        SUM(ISNULL(-ss.CostTotal, 0)) AS CostTotal,
                                        SUM(ISNULL(-ss.[BargainTotal], 0))
                                        - SUM(ISNULL(-ss.CostTotal, 0)) AS Profittotal,
                                        SUM(CASE WHEN vchtype IN ( 100, 101 )
                                                 THEN -( BargainTotal )
                                                 ELSE 0
                                            END) AS zgccTotal
                                FROM    Dlydata ss
                                WHERE   [date] BETWEEN @BeginDate AND @EndDate
                                        AND usedtype = CASE WHEN vchtype IN ( 222, 224 )
                                                            THEN 1
                                                            ELSE usedtype
                                                       END
                                        AND ss.billtype = 2
                                        AND ss.redold = 'F'
										AND ss.BranchId LIKE @BranchId + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 ) --单据类型	
	                                AND EXISTS ( SELECT GetID
	                                             FROM   FN_GetIdStrListTable(@vchtype) FilterVch
	                                             WHERE  ss.VchType = FilterVch.GetID )  --单据类型  
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B FilterB
	                                             WHERE  ss.BtypeId = FilterB.TypeId )
	                                             OR ss.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  ss.EtypeId = FilterE.TypeId )
	                                             OR ss.EtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_K FilterK
	                                             WHERE  ss.ktypeId = Filterk.KtypeId )
	                                             OR ss.KtypeId=''  	--收款单 仓库为空
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC FilterBC
	                                             WHERE  ss.Branchid = FilterBC.branchid )
                                GROUP BY [date]
                              ) ds ON ds.[date] = c.[date]
                    LEFT JOIN ( SELECT  [date],
                                        SUM(a.Total) AS ArTotal
                                FROM    dlya a
                                WHERE   a.atypeid = '0000100005'
                                        AND redold = 'F'
                                        AND [date] BETWEEN @BeginDate AND @EndDate
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 ) --单据类型   	
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )
                                GROUP BY [date]
                              ) da ON c.[date] = da.[date]
                    LEFT JOIN ( SELECT  [date],
                                        SUM(a.Total) AS ApTotal
                                FROM    dlya a
                                WHERE   a.atypeid = '0000200001'
                                        AND redold = 'F'
                                        AND [date] BETWEEN @BeginDate AND @EndDate
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 )   		   
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )
                                GROUP BY [date]
                              ) db ON c.[date] = db.[date]
                    LEFT JOIN ( SELECT  [date],
                                        SUM(CASE a.atypeid
                                              WHEN '0000299999' THEN -a.Total
                                              ELSE a.total
                                            END) AS HKTotal
                                FROM    dlya a
                                WHERE   ( LEFT(a.atypeid, 10) IN (
                                          '0000100003', '0000100004' )
                                          OR a.atypeid = '000040000300006'
                                          OR a.atypeid = '0000299999'
                                        )
                                        AND [date] BETWEEN @BeginDate AND @EndDate
                                        AND redold = 'F'
                                        AND Dtypeid LIKE @deptid + '%'
                                        AND vchtype IN ( 100, 101, 11, 45, 26, 24, 13, 12, 222, 224, 4, 36, 93, 115, 66 ) 		   
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_B1 FilterB
	                                             WHERE  a.BtypeId = FilterB.TypeId )
	                                             OR a.BtypeId=''  	
	                                )
	                                AND
	                                ( EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_E FilterE
	                                             WHERE  a.EtypeId = FilterE.TypeId )
	                                             OR a.EtypeId=''  	
	                                )
	                                AND  EXISTS ( SELECT 1
	                                             FROM   #SaleYMD_BC1 FilterBC
	                                             WHERE  a.Branchid = FilterBC.branchid )
                                GROUP BY [date]
                              ) back ON c.[date] = back.[date]  
 
            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].[FZQueryUser]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZQueryUser]
GO


CREATE PROCEDURE FZQueryUser
    (
      @szEtypeID VARCHAR(50),
      @OperatorId VARCHAR(50),
	  @showadmin int =1
    )
AS 
    IF @szEtypeid <> '' 
        BEGIN  
            SELECT  l.*,
                    --e.typeid AS etypeid,
                    b.BranchId,
                    ISNULL(b.FullName, '') AS BcFullName,
                    CASE LockId
                      WHEN '' THEN ''
                      ELSE '√'
                    END AS IfLocked,
                    CASE LockId
                      WHEN '' THEN ''
                      ELSE ( CASE LockLevel
                               WHEN 1 THEN '高级'
                               WHEN 0 THEN '普通'
                               ELSE ''
                             END )
                    END AS xLockLevel, dbo.GetIPlist(l.EtypeId) as ipaddrs 
            FROM    dbo.FN_GetPowerRangeEList(@szEtypeID, '') e
                    INNER JOIN loginuser l ON l.etypeid = e.typeid
                    LEFT JOIN ( SELECT  BranchId,
                                        FullName
                                FROM    Branch
                              ) b ON e.BranchId = b.BranchId  
			where  e.stop=0 and  l.etypeid <>case when @showadmin=1 then '' else '00000' end

        END   
    ELSE 
        BEGIN  
            SELECT  l.*,
                    b.BranchId,
                    ISNULL(b.FullName, '') AS BcFullName,
                    CASE LockId
                      WHEN '' THEN ''
                      ELSE '√'
                    END AS IfLocked,
                    CASE LockId
                      WHEN '' THEN ''
                      ELSE ( CASE LockLevel
                               WHEN 1 THEN '高级'
                               WHEN 0 THEN '普通'
                               ELSE ''
                             END )
                    END AS xLockLevel ,dbo.GetIPlist(l.EtypeId) as ipaddrs 
            FROM    loginuser l
                    LEFT JOIN employee e ON l.etypeid = e.typeid
                    LEFT JOIN ( SELECT  BranchId,
                                        FullName
                                FROM    Branch
                              ) b ON e.BranchId = b.BranchId  
			where  e.stop=0 and  l.etypeid <>case when @showadmin=1 then '' else '00000' end
        END  
    RETURN 0  






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[PtypeBuySale]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[PtypeBuySale]
GO

SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO
/*      
商品进销存分析
效率提升40%
*/      
Create PROC PtypeBuySale
(      
  @dynTable as DynParameterTable readonly
  , @sqlCmd nvarchar(max) out --输出参数, 业务Sql片段
  , @decSql nvarchar(max) out --输出参数，参数声明Sql片段
  , @specSql nvarchar(max) out --输出参数，参数赋值Sql片段    
)       
AS 
BEGIN
	DECLARE @SQLCmd1 VARCHAR(MAX),@SQLCmd2 VARCHAR(8000) = ''
	--新增存储过程 GetDig，用来取小数配置。以后所有报表存储过程对小数位的取舍用以下方式。
	DECLARE  @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
	EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
	SET @SQLCmd1 = N''
	set @decSql = N'@dynParamTable as DynParameterTable readonly,@dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int'
	set @specSql = N'@dynParamTable,'+ CAST(@dig_qty AS NVARCHAR)+N','+ CAST(@dig_price AS NVARCHAR)+N','+CAST(@dig_total AS NVARCHAR)+N','+CAST(@dig_dis AS NVARCHAR)+N','+
	CAST(@dig_tax AS NVARCHAR)+N','+CAST(@dig_rate AS NVARCHAR)
	
	SELECT @decSql += nchar(10) + nchar(9) + N', @' + ParaField + N' ' + DataType,
	       @specSql += nchar(10) + nchar(9) + isnull(N', ''' + ParaValue + N'''', ', null')
    from @dynTable
    WHERE datatype <> ''
    
    DECLARE @branchmode VARCHAR(10),@jmph VARCHAR(50),@cgjh VARCHAR(50)
    SELECT @branchmode = paraValue FROM @dynTable WHERE paraField = 'branchmode'
    
    IF @branchmode = '0'   --内部机构
    BEGIN
    	SET @cgjh = '6,34'
    	SET @jmph = '222,224'
    END
    ELSE
    BEGIN
    	SET @cgjh = '232,234'
    	SET @jmph = '0'
    END
    
    DECLARE @Branchid VARCHAR(50),@Ktypeid VARCHAR(50),@SalePriceid VARCHAR(50),
    @Ptypecategory VARCHAR(10),@ShowFields VARCHAR(8000),@WhereCmd VARCHAR(8000)= '',@GroupBy VARCHAR(8000)='',@OrderBy VARCHAR(3000) = '',@Flag BIT = 0,
    @temp1fields VARCHAR(2000) = '',@temp1groupby VARCHAR(2000) = '',@ckshowfields VARCHAR(2000) = '',@datawhere VARCHAR(2000)='',
    @otherfields VARCHAR(2000) = '',@otherwhere VARCHAR(2000)= '',@billwhere VARCHAR(2000) = '',@transbillwhere VARCHAR(2000) = '',
    @transjoin VARCHAR(2000) = '',@colorid VARCHAR(20)= '',@sizeid VARCHAR(20)= '',@tbl1where VARCHAR(2000) = '',@transsql VARCHAR(2000) = '',
    @priceModeSQL VARCHAR(2000) = '',@billwhere_before VARCHAR(2000) = ''
    
    SELECT @Branchid = ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'branchid'
    SET @Branchid = SUBSTRING(@Branchid,1,LEN(@Branchid)-1)
    SELECT @Ktypeid = ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'ktypeid'
    SELECT @colorid = ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'colorid'
    SELECT @sizeid = ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'sizeid'
    SELECT @SalePriceid = ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'salepriceid'
    SELECT @Ptypecategory = ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'ptypecategory' 
    SELECT @ShowFields = ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'dlistfield'       
    SELECT @ShowFields = @ShowFields + ',' + ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'ddistdetailfield'    
    
    IF @Ptypecategory = ''
    SET @Ptypecategory = '1'
    
    IF @colorid <> ''
    BEGIN
		SET @tbl1where = @tbl1where + ' and gsd.colorid = @colorid '
		SET	@temp1groupby = @temp1groupby + 'gsd.colorid, '
    END
    
	
	IF @sizeid <> ''
	BEGIN
		SET @tbl1where = @tbl1where + ' and gsd.sizeid = @sizeid '
		SET	@temp1groupby = @temp1groupby + 'gsd.sizeid, '
	END
	

    IF @Ktypeid <> ''
    BEGIN
    	SET @Ktypeid = SUBSTRING(@Ktypeid,1,LEN(@Ktypeid)-1)
    END
    
    
    DECLARE @pc1 VARCHAR(2),@pc2 VARCHAR(2),@pc3 VARCHAR(2)
	SELECT @pc1 = a FROM Fn_splitWithOrderid(@ptypecategory,',') WHERE orderid = 1
	SELECT @pc2 = a FROM Fn_splitWithOrderid(@ptypecategory,',') WHERE orderid = 2
	SELECT @pc3 = a FROM Fn_splitWithOrderid(@ptypecategory,',') WHERE orderid = 3
    
    DECLARE @sumFields VARCHAR(8000) = '',@sumGroupBy VARCHAR(5000) = ''
    
    IF CHARINDEX('ptypeid',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + 'dly.ptypeid,'
	SET @GroupBy = @GroupBy + 'dly.ptypeid,'
	SET @OrderBy = @OrderBy + 'DATA.ptypeid,'
	SET @sumFields = @sumFields + 'c.ptypeid,'
	SET @sumGroupBy = @sumGroupBy + 'c.ptypeid,'
	END
    
    IF CHARINDEX('btypeid',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(select btypeid1 from ptype where typeid = dly.ptypeid) btypeid,'
	SET @OrderBy = @OrderBy + 'DATA.btypeid,'
	SET @sumFields = @sumFields + 'c.btypeid,'
	SET @sumGroupBy = @sumGroupBy + 'c.btypeid,'	
	SET @Flag = 1
	END
    
    IF CHARINDEX('branchid',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + 'dly.BranchId,'
	SET @GroupBy = @GroupBy + 'dly.BranchId,'
	SET @OrderBy = @OrderBy + 'DATA.BranchId,'
	SET @sumFields = @sumFields + 'c.BranchId,'
	SET @sumGroupBy = @sumGroupBy + 'c.BranchId,'	
	SET @temp1fields = @temp1fields + 'st.branchid,'
	SET @datawhere = @datawhere + ' and a.branchid = b.branchid '
	SET @otherfields = @otherfields + ' b.branchid, '
	SET @otherwhere = @otherwhere + ' b.branchid, '
	SET @billwhere = @billwhere + ' and a.branchid = d.branchid '
	SET @billwhere_before = @billwhere_before + ' and a.branchid = f.branchid '
	SET @transbillwhere = @transbillwhere + ' and a.branchid = e.branchid '
	END
    
    IF CHARINDEX('colorid',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + 'RIGHT(''''00000''''+ CAST(dly.ColorID AS VARCHAR),5) colorid,'
	SET @GroupBy = @GroupBy + 'dly.ColorID,'
	SET @OrderBy = @OrderBy + 'DATA.ColorID,'
	SET @sumFields = @sumFields + 'c.ColorID,'
	SET @temp1fields = @temp1fields + 'gsd.ColorID,'
	SET @sumGroupBy = @sumGroupBy + 'c.ColorID,'		
	SET @datawhere = @datawhere + ' and a.ColorID = b.ColorID'
	SET @otherfields = @otherfields + 'c.colorid,'
	SET @otherwhere = @otherwhere + ' c.colorid, '
    SET @billwhere = @billwhere + ' and a.colorid = d.colorid '
    SET @billwhere_before = @billwhere_before + ' and a.colorid = f.colorid '
    SET @transbillwhere = @transbillwhere + ' and a.colorid = e.colorid '			
	END
    
    IF CHARINDEX('sizeid',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + 'RIGHT(''''00000''''+ CAST(dly.SizeID AS VARCHAR),5) sizeid,'
	SET @GroupBy = @GroupBy + 'dly.SizeID,'
	SET @OrderBy = @OrderBy + 'DATA.SizeID,'
	SET @sumFields = @sumFields + 'c.SizeID,'
	SET @sumGroupBy = @sumGroupBy + 'c.SizeID,'
	SET @temp1fields = @temp1fields + 'gsd.SizeID,'
	SET @datawhere = @datawhere + ' and a.SizeID = b.SizeID'
	SET @otherfields = @otherfields + 'c.SizeID,'
	SET @otherwhere = @otherwhere + 'c.SizeID,'
	SET @billwhere = @billwhere + ' and a.SizeID = d.SizeID '
	SET @billwhere_before = @billwhere_before + ' and a.SizeID = f.SizeID '
    SET @transbillwhere = @transbillwhere + ' and a.SizeID = e.SizeID '					
	END
    
    IF CHARINDEX('assist1',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 1) assist1,'
	SET @OrderBy = @OrderBy + 'DATA.assist1,'
	SET @sumFields = @sumFields + 'c.assist1,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist1,'
	SET @Flag = 1	
	END
    
    IF CHARINDEX('assist2',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 2) assist2,'
	SET @OrderBy = @OrderBy + 'DATA.assist2,'
	SET @sumFields = @sumFields + 'c.assist2,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist2,'
	SET @Flag = 1			
	END
    
    IF CHARINDEX('assist3',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 3) assist3,'
	SET @OrderBy = @OrderBy + 'DATA.assist3,'
	SET @sumFields = @sumFields + 'c.assist3,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist3,'		
	SET @Flag = 1	
	END
    
    IF CHARINDEX('assist4',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 4) assist4,'
	SET @OrderBy = @OrderBy + 'DATA.assist4,'
	SET @sumFields = @sumFields + 'c.assist4,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist4,'		
	SET @Flag = 1	
	END
    
    IF CHARINDEX('assist5',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 5) assist5,'
	SET @OrderBy = @OrderBy + 'DATA.assist5,'
	SET @sumFields = @sumFields + 'c.assist5,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist5,'			
	SET @Flag = 1	
	END
    
    IF CHARINDEX('assist6',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 6) assist6,'
	SET @OrderBy = @OrderBy + 'DATA.assist6,'
	SET @sumFields = @sumFields + 'c.assist6,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist6,'			
	SET @Flag = 1	
	END
    
    IF CHARINDEX('assist7',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 7) assist7,'
	SET @OrderBy = @OrderBy + 'DATA.assist7,'
	SET @sumFields = @sumFields + 'c.assist7,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist7,'			
	SET @Flag = 1	
	END
	
    IF CHARINDEX('assist8',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 8) assist8,'
	SET @OrderBy = @OrderBy + 'DATA.assist8,'
	SET @sumFields = @sumFields + 'c.assist8,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist8,'			
	SET @Flag = 1	
	END
	
	IF CHARINDEX('ptypecategory',@ShowFields)>0
	BEGIN
		IF @pc1 <> '0'
		BEGIN
			SET @SQLCmd2 = @SQLCmd2 + 'left(dly.ptypeid,'+ @pc1 +'*5) ptypeid1,'
	        SET @OrderBy = @OrderBy + 'DATA.ptypeid1,'
	        SET @sumFields = @sumFields + 'c.ptypeid1,'
	   	    SET @sumGroupBy = @sumGroupBy + 'c.ptypeid1,'     
	        SET @Flag = 1	
		END
	    
		IF @pc2 <> '0'
		BEGIN
			SET @SQLCmd2 = @SQLCmd2 + 'left(dly.ptypeid,'+ @pc2 +'*5) ptypeid2,'
	        SET @OrderBy = @OrderBy + 'DATA.ptypeid2,'
	        SET @sumFields = @sumFields + 'c.ptypeid2,'
	   	    SET @sumGroupBy = @sumGroupBy + 'c.ptypeid2,' 	        			
			SET @Flag = 1
		END
		
		IF @pc3 <> '0'
		BEGIN
			SET @SQLCmd2 = @SQLCmd2 + 'left(dly.ptypeid,'+ @pc3 +'*5) ptypeid3,'
	        SET @OrderBy = @OrderBy + 'DATA.ptypeid3,'
	        SET @sumFields = @sumFields + 'c.ptypeid3,'
	   	    SET @sumGroupBy = @sumGroupBy + 'c.ptypeid3,' 	        			
			SET @Flag = 1
		END
	END
	
    IF CHARINDEX('dly.ptypeid',@GroupBy)=0 
	BEGIN
		IF @Flag = 1
		BEGIN
			SET @GroupBy = @GroupBy + 'dly.ptypeid,'
		END
	END

	IF CHARINDEX('qty',@ShowFields)>0 
    BEGIN
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__cgjh__) THEN  SUM(dly.Qty) ELSE 0 END cgjhqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 1) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 1)) THEN SUM(dly.Qty) ELSE 0 END phjhqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 3) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 3)) THEN SUM(dly.Qty) ELSE 0 END dpjhqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 2) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 2)) THEN SUM(dly.Qty) ELSE 0 END thjhqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218,__cgjh__)) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode)) THEN SUM(dly.Qty) ELSE 0 END jhhjqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (12,100) THEN SUM(-dly.Qty) ELSE 0 END lsqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (11,24,45) THEN SUM(-dly.Qty) ELSE 0 END pfxsqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__jmph__) THEN SUM(-dly.Qty) ELSE 0 END jmphqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__jmph__,12,100,11,24,45) THEN SUM(-dly.Qty) ELSE 0 END xshjqty,'
			--SET @SQLCmd2 = @SQLCmd2 + 'SUM(f.Qty) kcqty,'
			SET @ckshowfields = @ckshowfields + 'ISNULL(b.kcqty,0)-ISNULL(d.qty,0) kcqty,'
			SET @ckshowfields = @ckshowfields + 'ISNULL(b.kcqty,0)-ISNULL(f.qty,0) kcsqqty,'
			SET @sumFields = @sumFields + 'sum(c.cgjhqty) cgjhqty,sum(c.phjhqty) phjhqty,sum(c.dpjhqty) dpjhqty,sum(c.thjhqty) thjhqty,sum(c.jhhjqty) jhhjqty,sum(c.lsqty) lsqty,sum(c.pfxsqty) pfxsqty,sum(c.jmphqty) jmphqty,sum(c.xshjqty) xshjqty,'
	END
	
	IF CHARINDEX('total',@ShowFields)>0 
    BEGIN
		IF @SalePriceid = '' --单据单价
		BEGIN
		    SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__cgjh__) THEN  ROUND( CONVERT(NUMERIC(24,10),SUM(dly.BargainTotal)),@dig_total) ELSE 0 END cgjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 1) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 1)) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.BargainTotal)),@dig_total) ELSE 0 END phjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 3) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 3)) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.BargainTotal)),@dig_total) ELSE 0 END dpjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 2) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 2)) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.BargainTotal)),@dig_total) ELSE 0 END thjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218,__cgjh__)) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode)) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.BargainTotal)),@dig_total) ELSE 0 END jhhjtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (12,100) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.BargainTotal)),@dig_total) ELSE 0 END lstotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (11,24,45) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.BargainTotal)),@dig_total) ELSE 0 END pfxstotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__jmph__) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.BargainTotal)),@dig_total) ELSE 0 END jmphtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__jmph__,12,100,11,24,45) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.BargainTotal)),@dig_total) ELSE 0 END xshjtotal,'
			SET @otherFields =  @otherFields +' sum(c.costtotal) total,'
			SET @priceModeSQL = @priceModeSQL + 'sum(isnull(gsd.total,0)) kctotal,'
		END
		ELSE    --其他参考价
		BEGIN
		    SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__cgjh__) THEN  ROUND( CONVERT(NUMERIC(24,10),SUM(dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END cgjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 1) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 1)) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END phjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 3) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 3))THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END dpjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 2) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 2))THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END thjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218,__cgjh__)) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode)) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END jhhjtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (12,100) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END lstotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (11,24,45) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END pfxstotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__jmph__) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END jmphtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__jmph__,12,100,11,24,45) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END xshjtotal,'
			SET @otherFields =  @otherFields +' ROUND(CONVERT(NUMERIC(24,10),sum(c.qty))*ISNULL(d.price,0),@dig_total) total,'
			SET @priceModeSQL = @priceModeSQL + 'CONVERT(NUMERIC(24,10),SUM(ISNULL(gsd.Qty,0)*ISNULL(' + CASE WHEN @SalePriceid = ''  then 'gs.price' else 'd.Price' END + ',0))) kctotal,'
		END
			--SET @SQLCmd2 = @SQLCmd2 + 'SUM(f.Qty*ISNULL(d.Price,0)) kctotal,'
			SET @ckshowfields = @ckshowfields + 'ISNULL(b.kctotal,0) - ISNULL(d.total,0) kctotal,'
			SET @ckshowfields = @ckshowfields + 'ISNULL(b.kctotal,0) - ISNULL(f.total,0) kcsqtotal,'
			SET @sumFields = @sumFields + 'sum(c.cgjhtotal) cgjhtotal,sum(c.phjhtotal) phjhtotal,sum(c.dpjhtotal) dpjhtotal,sum(c.thjhtotal) thjhtotal,sum(c.jhhjtotal) jhhjtotal,sum(c.lstotal) lstotal,sum(c.pfxstotal) pfxstotal,sum(c.jmphtotal) jmphtotal,sum(c.xshjtotal) xshjtotal,'
	END
	
	IF CHARINDEX('total',@ShowFields)>0 OR CHARINDEX('qty',@ShowFields)>0
		SET @GroupBy = @GroupBy + 'dly.phid,dly.dlyvchcode,'
		
	IF @SalePriceid <> ''
	--BEGIN
	--	SET @GroupBy = @GroupBy + 'b.costprice,'
	--	--SET @temp1fields = @temp1fields + 'gs.price,'
	--END
	--ELSE
	BEGIN
		SET @GroupBy = @GroupBy + 'dly.price,'
		SET @otherwhere = @otherwhere + 'd.price,'
		--SET @temp1fields = @temp1fields + 'd.price,'
	END		

	IF @Branchid = '00001' AND @Ktypeid = ''
	BEGIN
		SET @transjoin = @transjoin + ' LEFT JOIN #billtrans e ON e.ptypeid = a.ptypeid__transwhere__ '
		SET @transSql = @transSql + '
			--在途库
			IF object_id(''''tempdb..#billtrans'''') is not null   
			drop table #billtrans
			select tbl.* into #billtrans from (
				select __otherFileds__b.ptypeid,sum(c.qty) qty
				from dlyndx a inner join dlydata b on a.vchcode = b.vchcode
				inner join dlydatadetail c on b.dlyorder = c.dlyorder
				left join dbo.PtypePrice d ON d.Ptypeid = b.PtypeId AND d.PriceTypeid = @salepriceid
				where CASE WHEN (b.VchType IN (224,232) OR (b.Vchtype IN (212,218) AND (b.Usedtype=''''2'''' OR (b.Usedtype=''''3'''' AND c.Qty<0)))) THEN CONVERT(varchar(12) ,a.checkdate, 23 ) WHEN b.Vchtype = 230 THEN CONVERT(varchar(12) ,a.AccountTime, 23 ) ELSE b.[date] END > @billdate_e
				and a.draft = 4
				AND (@ptypeid IS NULL OR b.Ptypeid LIKE @ptypeid)
				'+CASE WHEN @Ktypeid IS NULL OR @Ktypeid='' THEN '' ELSE ' AND b.Ktypeid like @ktypeid' END +
				  CASE WHEN @colorid IS NULL OR @colorid='' THEN '' ELSE ' AND c.ColorID = @colorid' END +
				  CASE WHEN @sizeid IS NULL OR @sizeid='' THEN '' ELSE ' AND c.SizeID = @sizeid' END +'
				AND EXISTS(SELECT 1 FROM dbo.FN_GetStockListOfBranch(@oprid,'''''''','''''''') WHERE KtypeId = b.KtypeId)
				AND EXISTS(SELECT 1 FROM #tmpptype WHERE TypeID = b.PtypeId)
				and b.ktypeid = ''''99999''''
				and a.redold = ''''F''''
				and a.vchtype in (212,218,222,234) 
				group by __otherwhere__b.ptypeid
			) tbl'
	END

	SET @SQLCmd1 = '
		IF OBJECT_ID(''''tempdb..#tmpptype'''') is not null drop table #tmpptype
		create table #tmpptype (typeid varchar(50))
		
		IF EXISTS (SELECT name FROM sys.indexes
            WHERE name = N''''IX_PtypeBuySale_TypeID'''')
			DROP INDEX IX_PtypeBuySale_TypeID ON #tmpptype;
		CREATE CLUSTERED INDEX IX_PtypeBuySale_TypeID 
			ON #tmpptype(typeid); 
			
		insert into #tmpptype(typeid)
		select typeid from dbo.FN_GetPowerRangePList(@oprid,'''''''')


		IF OBJECT_ID(''''tempdb..#dlyptype'''') is not null drop table #dlyptype
		create table #dlyptype (ptypeid varchar(50),
								branchid varchar(50),
								colorid varchar(50),
								sizeid varchar(50),
								qty NUMERIC(24,10),
								BargainTotal NUMERIC(24,10),
								vchtype int,
								vchcode int,
								phid int,
								dlyvchcode int,
								ktypeid varchar(50),
								price NUMERIC(24,10))

		insert into #dlyptype(ptypeid,
							  branchid,
							  colorid,
							  sizeid,
							  qty,
							  BargainTotal,
							  vchtype,
							  vchcode,
							  phid,
							  dlyvchcode,
							  ktypeid,
							  price
							  )
		select b.ptypeid,b.branchid,c.colorid,c.sizeid,
		case when a.vchtype in (212,218) and a.draft = 2 and a.branchid = b.branchid then c.qty
		     when a.vchtype not in (212,218) then c.qty
			 else 0 end qty,
		case when a.vchtype in (212,218) and a.draft = 2 and a.branchid = b.branchid then c.BargainTotal 
		     when a.vchtype not in (212,218) then c.BargainTotal
		     else 0 end BargainTotal,
		a.vchtype,a.vchcode,a.phid,a.dlyvchcode,b.ktypeid,ISNULL(d.price,0)
		FROM DlyNdx a INNER JOIN dbo.DlyData b ON a.vchcode = b.vchcode
		INNER JOIN dbo.DlyDataDetail c ON b.DlyOrder = c.DlyOrder
		LEFT JOIN dbo.PtypePrice d ON d.Ptypeid = b.PtypeId AND d.PriceTypeid = @salepriceid
		WHERE CASE WHEN (b.VchType IN (224,232) OR (b.Vchtype IN (212,218) AND (b.Usedtype=''''2'''' OR (b.Usedtype=''''3'''' AND c.Qty<0)))) THEN CONVERT(varchar(12) ,a.checkdate, 23 ) WHEN b.Vchtype = 230 THEN CONVERT(varchar(12) ,a.AccountTime, 23 ) ELSE b.[date] END BETWEEN @billdate_s AND @billdate_e
		AND a.Vchtype IN (6,11,12,24,34,45,100,212,218,222,224,232,234,230)
		AND a.Draft IN (2,4)
		AND a.Redold = ''''F''''
	    AND (@branchid IS NULL OR b.Branchid LIKE @branchid)
	    '+CASE WHEN @Ktypeid IS NULL OR @Ktypeid='' THEN '' ELSE ' AND b.Ktypeid like @ktypeid' END +
		  CASE WHEN @colorid IS NULL OR @colorid='' THEN '' ELSE ' AND c.ColorID = @colorid' END +
		  CASE WHEN @sizeid IS NULL OR @sizeid='' THEN '' ELSE ' AND c.SizeID = @sizeid' END +'
		AND (@ptypeid IS NULL OR b.Ptypeid LIKE @ptypeid)
		AND b.KtypeId <> ''''99999''''
		
		--删除数量为0的数据
		delete from #dlyptype where qty = 0
		
	    --单据数量金额 结束日期之后数据
		IF object_id(''''tempdb..#billtbl'''') is not null   
		drop table #billtbl
		select tbl.* into #billtbl from (
			select __otherFileds__b.ptypeid,sum(c.qty) qty
			from dlyndx a inner join dlydata b on a.vchcode = b.vchcode
			inner join dlydatadetail c on b.dlyorder = c.dlyorder
			left join dbo.PtypePrice d ON d.Ptypeid = b.PtypeId AND d.PriceTypeid = @salepriceid
			where CASE WHEN (b.VchType IN (224,232) OR (b.Vchtype IN (212,218) AND (b.Usedtype=''''2'''' OR (b.Usedtype=''''3'''' AND c.Qty<0)))) THEN CONVERT(varchar(12) ,a.checkdate, 23 ) WHEN b.Vchtype = 230 THEN CONVERT(varchar(12) ,a.AccountTime, 23 ) ELSE b.[date] END > @billdate_e
			and a.draft in (2,4)
			AND (@branchid IS NULL OR b.Branchid LIKE @branchid) '
			+ CASE WHEN @Ktypeid IS NULL OR @Ktypeid='' THEN '' ELSE ' AND b.Ktypeid like @ktypeid' END +
			  CASE WHEN @colorid IS NULL OR @colorid='' THEN '' ELSE ' AND c.ColorID = @colorid' END +
			  CASE WHEN @sizeid IS NULL OR @sizeid='' THEN '' ELSE ' AND c.SizeID = @sizeid' END +'
			AND (@ptypeid IS NULL OR b.Ptypeid LIKE @ptypeid)
			AND EXISTS(SELECT 1 FROM dbo.FN_GetStockListOfBranch(@oprid,'''''''','''''''') WHERE KtypeId = b.KtypeId)
		    AND EXISTS(SELECT 1 FROM #tmpptype WHERE TypeID = b.PtypeId)
			and b.ktypeid <> ''''99999''''
			and a.redold = ''''F''''
			and a.vchtype in (6,9,11,12,14,16,17,21,24,34,45,57,100,126,139,150,212,218,222,224,230,234,251,252) 
			group by __otherwhere__b.ptypeid
		) tbl

	    --单据数量金额 开始日期之后数据
		IF object_id(''''tempdb..#billtbl_before'''') is not null   
		drop table #billtbl_before
		select tbl.* into #billtbl_before from (
			select __otherFileds__b.ptypeid,sum(c.qty) qty
			from dlyndx a inner join dlydata b on a.vchcode = b.vchcode
			inner join dlydatadetail c on b.dlyorder = c.dlyorder
			left join dbo.PtypePrice d ON d.Ptypeid = b.PtypeId AND d.PriceTypeid = @salepriceid
			where CASE WHEN (b.VchType IN (224,232) OR (b.Vchtype IN (212,218) AND (b.Usedtype=''''2'''' OR (b.Usedtype=''''3'''' AND c.Qty<0)))) THEN CONVERT(varchar(12) ,a.checkdate, 23 ) WHEN b.Vchtype = 230 THEN CONVERT(varchar(12) ,a.AccountTime, 23 ) ELSE b.[date] END >= @billdate_s
			and a.draft in (2,4)
			AND (@branchid IS NULL OR b.Branchid LIKE @branchid) '
			+ CASE WHEN @Ktypeid IS NULL OR @Ktypeid='' THEN '' ELSE ' AND b.Ktypeid like @ktypeid' END +
			  CASE WHEN @colorid IS NULL OR @colorid='' THEN '' ELSE ' AND c.ColorID = @colorid' END +
			  CASE WHEN @sizeid IS NULL OR @sizeid='' THEN '' ELSE ' AND c.SizeID = @sizeid' END +'
			AND (@ptypeid IS NULL OR b.Ptypeid LIKE @ptypeid)
			AND EXISTS(SELECT 1 FROM dbo.FN_GetStockListOfBranch(@oprid,'''''''','''''''') WHERE KtypeId = b.KtypeId)
		    AND EXISTS(SELECT 1 FROM #tmpptype WHERE TypeID = b.PtypeId)
			and b.ktypeid <> ''''99999''''
			and a.redold = ''''F''''
			and a.vchtype in (6,9,11,12,14,16,17,21,24,34,45,57,100,126,139,150,212,218,222,224,230,234,251,252) 
			group by __otherwhere__b.ptypeid
		) tbl

		__transql__

		IF object_id(''''tempdb..#tbl'''') is not null   
		drop table #tbl
		select tbl.* into #tbl from(
		SELECT __Fields__              
		FROM #dlyptype dly
		where (@btypeid is NULL OR EXISTS (SELECT 1 FROM dbo.Ptype p WHERE p.typeid = dly.ptypeid AND p.btypeid1 like @btypeid ))
		AND EXISTS (SELECT 1 FROM dbo.Ptype p WHERE p.TypeId =dly.Ptypeid AND p.[stop] IN (CASE p.stop when 1 then @containsstop else 0 end)) 
		AND (@assist1 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist1))
		AND (@assist2 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist2))
		AND (@assist3 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist3))
		AND (@assist4 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist4))
		AND (@assist5 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist5))
		AND (@assist6 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist6))
		AND (@assist7 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist7))
		AND (@assist8 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist8))
		AND EXISTS(SELECT 1 FROM dbo.FN_GetStockListOfBranch(@oprid,'''''''','''''''') WHERE KtypeId = dly.KtypeId)
		AND EXISTS(SELECT 1 FROM #tmpptype WHERE TypeID = dly.PtypeId)
		GROUP BY __groupby__dly.vchtype,dly.vchcode
	) tbl
	
	IF object_id(''''tempdb..#tbl1'''') is not null   
	drop table #tbl1
	select tbl1.* into #tbl1 from(
	SELECT __temp1fields__gs.PtypeId,__kctotal__sum(ISNULL(gsd.Qty,0)) kcqty
	FROM dbo.GoodsStocks gs INNER JOIN dbo.Goodsstockdetail gsd ON gs.OrderId = gsd.OrderId
	inner join dbo.Stock st on gs.ktypeid = st.typeid
	LEFT JOIN dbo.PtypePrice d ON d.Ptypeid = gs.PtypeId AND d.PriceTypeid = @salepriceid
	WHERE EXISTS(SELECT 1 FROM dbo.FN_GetStockListOfBranch(@oprid,'''''+ @Branchid +''''',''''' + @Ktypeid + ''''') fn WHERE fn.KtypeId = gs.ktypeid)
	AND EXISTS(SELECT 1 FROM #tmpptype WHERE TypeID = gs.PtypeId)
	__tbl1where__
	group by __temp1groupby__gs.ptypeid
	) tbl1;
	
	with Data AS (
		select __datafields__a.*
		from (select __sumField__
				from #tbl c
				group by __sumgroup__) a LEFT JOIN #tbl1 b ON a.ptypeid = b.ptypeid __datawhere__
				LEFT JOIN #billtbl d ON a.ptypeid = d.ptypeid__billwhere__
				LEFT JOIN #billtbl_before f ON a.ptypeid = f.ptypeid__billwherebefore__
				__trans__
		),'
   
   	-- 排序信息
	declare @sortInfo varchar(255) = isnull((select ParaValue from @dynTable where ParaField = '__SortInfo__') + ',', '')
	-- 排序联接信息
	declare @sortJoinInfo varchar(555) = isnull((select replace(ParaValue, '__LeftTable__', 'Data') from @dynTable where ParaField = '__SortJoinInfo__'), '')
   
   set @sqlCmd = cast(
	(
		@SQLCmd1
		+ '
		__ReportData__ AS (
		select dense_rank() over (order by ' + @sortInfo + '__orderby__ DESC) __RowNo__,DATA.*
		from Data ' + @sortJoinInfo + ')'
	) as nvarchar(max))
   
   SET @SQLCmd2 = SUBSTRING(@SQLCmd2,1,LEN(@SQLCmd2)-1)
   set @sqlCmd = replace(@sqlCmd,'__Fields__',@SQLCmd2)
   --SET @GroupBy = SUBSTRING(@GroupBy,1,LEN(@GroupBy)-1)
   set @sqlCmd = replace(@sqlCmd,'__groupby__',@GroupBy)
   SET @OrderBy = SUBSTRING(@OrderBy,1,LEN(@OrderBy)-1)
   SET @sumFields = SUBSTRING(@sumFields,1,LEN(@sumFields)-1)
   SET @sumGroupBy = SUBSTRING(@sumGroupBy,1,LEN(@sumGroupBy)-1)
   set @sqlCmd = replace(@sqlCmd,'__orderby__',@OrderBy)
   set @sqlCmd = replace(@sqlCmd,'__sumField__',@sumFields)
   set @sqlCmd = replace(@sqlCmd,'__sumgroup__',@sumGroupBy)      
   set @sqlCmd = replace(@sqlCmd,'__temp1fields__',@temp1fields)
   set @sqlCmd = replace(@sqlCmd,'__temp1groupby__',@temp1fields)
   set @sqlCmd = replace(@sqlCmd,'__datafields__',@ckshowfields)
   set @sqlCmd = replace(@sqlCmd,'__datawhere__',@datawhere) 
   set @sqlCmd = replace(@sqlCmd,'__transql__',@transSql)
   set @sqlCmd = replace(@sqlCmd,'__trans__',@transjoin)
   set @sqlCmd = replace(@sqlCmd,'__otherFileds__',@otherFields) 
   set @sqlCmd = replace(@sqlCmd,'__otherwhere__',@otherwhere)
   set @sqlCmd = replace(@sqlCmd,'__billwhere__',@billwhere)
   set @sqlCmd = replace(@sqlCmd,'__billwherebefore__',@billwhere_before)
   set @sqlCmd = replace(@sqlCmd,'__transwhere__',@transbillwhere)
   set @sqlCmd = replace(@sqlCmd,'__cgjh__',@cgjh)
   set @sqlCmd = replace(@sqlCmd,'__jmph__',@jmph)
   set @sqlCmd = replace(@sqlCmd,'__tbl1where__',@tbl1where)
   set @sqlCmd = replace(@sqlCmd,'__kctotal__',@priceModeSQL)
   
   
END
GO
/****** Object:  StoredProcedure [dbo].[FzGetAllPowerPro]    Script Date: 03/13/2012 16:01:35 ******/


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZGetCurrentTotal]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
  DROP PROCEDURE [dbo].[FZGetCurrentTotal]
GO




--取得在某一个时间一个或一类商品的库存，一个单位的应收余额，一个科目的余额
CREATE  PROCEDURE FZGetCurrentTotal
(
 @szSelect VARCHAR(50),
 @szAtypeid VARCHAR(50),
 @szPtypeid VARCHAR(50),
 @szBtypeid VARCHAR(50),
 @szEtypeid VARCHAR(50),
 @szKtypeid VARCHAR(50),
 @Enddate VARCHAR(10),
 @dQty NUMERIC(24, 10) OUTPUT,
 @dTotal NUMERIC(24, 10) OUTPUT,
 @BranchId VARCHAR(50),
 @OperatorId VARCHAR(50),
 @IsStop BIT = 0,--是否包含停用商品 0：包含  1：不包含
 @includeYS BIT = 0 ,	--是否包含预收款 ：1包含 0不包含
 @includeYF BIT = 0	--是否包含预付款 ：1包含 0不包含    
)
AS 
DECLARE @AR_ID VARCHAR(50)
DECLARE @AP_ID VARCHAR(50)
DECLARE @dTempAr NUMERIC(24, 10)
DECLARE @dTempAp NUMERIC(24, 10),
	@PreAr NUMERIC(24, 10),
	@PreAp NUMERIC(24, 10),
	@FZCS int
DECLARE @nPSon INT
DECLARE @nBSon INT
SELECT  @AR_ID = '0000100005'
SELECT  @AP_ID = '0000200001'

IF EXISTS(SELECT * FROM sysdata WHERE SubName = 'proctypename' AND SubValue = 'FZCS')
SELECT @FZCS = 1
ELSE SELECT @FZCS = 0
    
IF @szSelect = 'btype' 
  BEGIN
    SELECT  @nBSon = [sonnum]
    FROM    btype
    WHERE   [typeid] = (CASE @szBtypeid
                          WHEN '' THEN '00000'
                          ELSE @szBtypeid
                        END)
    IF @nBSon > 0 
      BEGIN
        SELECT  @dTotal = ISNULL(SUM(CASE atypeid WHEN '0000200888' THEN -total ELSE total end), 0)
        FROM    dlya
        WHERE   [date] >= @Enddate AND RedOld = 'F'
                AND btypeid LIKE @szBtypeid + '%'
                AND ((atypeid = @AR_ID AND @includeYS = 0) OR ((atypeid = @AR_ID OR atypeid = '0000200888') AND @includeYS = 1))
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = dlya.branchid ))
                	OR
                	(@FZCS = 1 AND dlya.branchid LIKE @BranchId + '%')
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = dlya.BranchID
                                    AND iniover = 1 )
                            
        SELECT  @dQty = ISNULL(SUM(CASE atypeid WHEN '0000100888' THEN -total ELSE total end), 0)
        FROM    dlya
        WHERE   [date] >= @Enddate AND RedOld = 'F'
                AND btypeid LIKE @szBtypeid + '%'
                AND ((atypeid = @Ap_ID AND @includeYF = 0) OR ((atypeid = @Ap_ID OR atypeid = '0000100888') AND @includeYF = 1))
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = dlya.branchid ))
                	OR
                	(@FZCS = 1 AND dlya.branchid LIKE @BranchId + '%')
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = dlya.BranchID
                                    AND iniover = 1 )
                            
        SELECT  @dTotal = @dTotal - @dQty
        SELECT  @dTempAr = ISNULL(SUM(bb.artotal), 0),
                @dTempAp = ISNULL(SUM(bb.aptotal), 0),
                @PreAr = SUM(ISNULL(bb.deposit,0)),
                @PreAp = SUM(ISNULL(bb.prepayment,0))
                --SELECT * FROM dbo.BranchBtype
        FROM    btype b
        LEFT JOIN BranchBtype bb
        ON      b.TypeId = bb.Btypeid
                AND bb.BranchId LIKE @BranchID + '%'
        WHERE   b.typeid LIKE @szBtypeid + '%'
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = bb.branchid ))
                	OR
                	(@FZCS = 1 AND 1=1)
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = bb.BranchID
                                    AND iniover = 1 )
          
        SELECT  @dTotal = (@dTempAr - @dTempAp) - @dTotal
        IF   @includeYF = 1 SELECT @dTotal = @dTotal + @PreAp
        IF   @includeYS = 1 SELECT @dTotal = @dTotal - @PreAr
        SELECT  @dQty = @dTotal
        RETURN 0
      END
    ELSE 
      BEGIN
        SELECT  @dTotal = ISNULL(SUM(CASE atypeid WHEN '0000200888' THEN -total ELSE total end), 0)
        FROM    dlya
        WHERE   [date] >= @Enddate AND RedOld = 'F'
                AND btypeid = @szBtypeid
                AND ((atypeid = @AR_ID AND @includeYF = 0) OR ((atypeid = @AR_ID OR atypeid = '0000200888') AND @includeYF = 1))
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = dlya.branchid ))
                	OR
                	(@FZCS = 1 AND dlya.branchid LIKE @BranchId + '%')
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = dlya.BranchID
                                    AND iniover = 1 )
                            
        SELECT  @dQty = ISNULL(SUM(CASE atypeid WHEN '0000100888' THEN -total ELSE total end), 0)
        FROM    dlya
        WHERE   [date] >= @Enddate AND RedOld = 'F'
                AND btypeid = @szBtypeid
                AND ((atypeid = @Ap_ID AND @includeYF = 0) OR ((atypeid = @Ap_ID OR atypeid = '0000100888') AND @includeYF = 1))
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = dlya.branchid ))
                	OR
                	(@FZCS = 1 AND dlya.branchid LIKE @BranchId + '%')
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = dlya.BranchID
                                    AND iniover = 1 )
                            
        SELECT  @dTotal = @dTotal - @dQty
        SELECT  @dTempAr = ISNULL(SUM(bb.artotal), 0),
                @dTempAp = ISNULL(SUM(bb.aptotal), 0),
                @PreAr = SUM(ISNULL(bb.deposit,0)),
                @PreAp = SUM(ISNULL(bb.prepayment,0))
        FROM    btype b
        LEFT JOIN BranchBtype bb
        ON      b.TypeId = bb.Btypeid
                AND bb.BranchId LIKE @BranchID + '%'
        WHERE   b.typeid = @szBtypeid
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = bb.branchid ))
                	OR
                	(@FZCS = 1 AND 1=1)
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = bb.BranchID
                                    AND iniover = 1 )
                            
        SELECT  @dTotal = (@dTempAr - @dTempAp) - @dTotal
        IF   @includeYF = 1 SELECT @dTotal = @dTotal + @PreAp
        IF   @includeYS = 1 SELECT @dTotal = @dTotal - @PreAr
        SELECT  @dQty = @dTotal
        RETURN 0
      END
  END
-------------------------------------------------------
IF @szSelect = 'etype' 
  BEGIN
    SELECT  @nBSon = [sonnum]
    FROM    employee
    WHERE   [typeid] = @szEtypeid
    IF @nBSon > 0
      AND @szEtypeid <> '00000' 
      BEGIN
        SELECT  @dTotal = SUM(ISNULL(total, 0))
        FROM    dlya
        WHERE   [date] <= @Enddate AND RedOld = 'F'
                AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                AND atypeid IN (@AR_ID, @AP_ID)  
        SELECT  @dQty = SUM(ISNULL(total, 0))
        FROM    dlya
        WHERE   [date] <= @Enddate AND RedOld = 'F'
                AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                AND atypeid IN (@AR_ID, @AP_ID)
        IF @dQty > 0 
          SELECT  @dTotal = -@dQty

        IF LEFT(@szBtypeid, 5) = '00001'
          AND @szatypeid = '0000200001' --应付
          BEGIN
            SELECT  @dTotal = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000200001'
            SELECT  @dTempAp = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000100005'
            SELECT  @dTempAp = ISNULL(@dTempAp, 0)
            SELECT  @dTotal = -(@dTotal - @dTempAp)

          END
        IF LEFT(@szBtypeid, 5) <> '00001'
          AND @szatypeid = '0000100005' --应收
          BEGIN
            SELECT  @dQty = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000100005'
            SELECT  @dTempAp = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000200001'
            SELECT  @dTempAp = ISNULL(@dTempAp, 0)
            SELECT  @dQty = ISNULL(@dQty, 0) - @dTempAp

          END
        IF @dQty <> 0 
          SELECT  @dTotal = @dQty
        SELECT  @dTotal = ISNULL(@dTotal, 0)
        SELECT  @dQty = ISNULL(@dQty, 0)
      END
    ELSE 
      BEGIN
        IF LEFT(@szBtypeid, 5) = '00001'
          AND @szatypeid = '0000200001' --应付
          BEGIN
            SELECT  @dTotal = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND etypeid = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000200001'
            SELECT  @dTempAp = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND etypeid = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000100005'
            SELECT  @dTempAp = ISNULL(@dTempAp, 0)
            SELECT  @dTotal = -(ISNULL(@dTotal, 0) - @dTempAp)

          END
        IF LEFT(@szBtypeid, 5) <> '00001'
          AND @szatypeid = '0000100005' --应收
          BEGIN
            SELECT  @dQty = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND etypeid = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000100005'
            SELECT  @dTempAp = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND etypeid = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000200001'
            SELECT  @dTempAp = ISNULL(@dTempAp, 0)
            SELECT  @dQty = @dQty - @dTempAp

          END
        IF @dQty <> 0 
          SELECT  @dTotal = @dQty
        SELECT  @dTotal = ISNULL(@dTotal, 0)
        SELECT  @dQty = ISNULL(@dQty, 0)
        RETURN 0
      END
  END
-----------------------------------------------------------
ELSE 
  IF @szSelect = 'ptype' 
    BEGIN
      SELECT  @nPSon = sonnum
      FROM    ptype
      WHERE   typeid = @szPtypeid
      IF @szKtypeid = '00000' 
        SET @szKtypeid = ''
      IF @szBtypeid = '00000' 
        SET @szBtypeid = ''
      IF @szKtypeid <> '00000'
        AND @szKtypeid <> '99999' 
        BEGIN
          IF @nPSon > 0 
            BEGIN
              SELECT  @dQty = ISNULL(SUM(qty), 0),
                      @dTotal = ISNULL(SUM(total), 0)
              FROM    goodsstocks a
              INNER JOIN Ptype p
              ON      a.PtypeId = p.TypeID
              WHERE   EXISTS ( SELECT 1
                               FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                               WHERE  Ktypeid = a.Ktypeid )
                      AND LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                      AND p.Stop IN (CASE @IsStop
                                       WHEN 0 THEN p.stop
                                       ELSE 0
                                     END)--是否包含停用商品

              SELECT  @dTempar = ISNULL(SUM(a.qty), 0),
                      @dTempap = ISNULL(SUM(a.costtotal), 0)
              FROM    DlyData a
              LEFT JOIN dbo.DlyNdx c ON a.Vchcode =c.Vchcode
              INNER JOIN Ptype p ON a.PtypeId = p.TypeID
              WHERE   --[date] >= @enddate 
                      CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND a.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END >= @enddate 
                      AND a.RedOld = 'F'
                      AND EXISTS ( SELECT 1
                                   FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                   WHERE  Ktypeid = a.Ktypeid )
                      AND LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                      AND pdetail <> 2
                      AND a.Vchtype NOT IN ('73', '89')
                      AND p.Stop IN (CASE @IsStop
                                       WHEN 0 THEN p.stop
                                       ELSE 0
                                     END)--是否包含停用商品
                                        
              SELECT  @dQty = ISNULL(@dQty, 0) - ISNULL(@dTempar, 0)
              SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)
            END
          ELSE 
            BEGIN
              SELECT  @dQty = ISNULL(SUM(qty), 0),
                      @dTotal = ISNULL(SUM(total), 0)
              FROM    goodsstocks a
              WHERE   EXISTS ( SELECT 1
                               FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid) s
                               WHERE  s.Ktypeid = a.Ktypeid )
                      AND ptypeid = @szPtypeid

              SELECT  @dTempar = ISNULL(SUM(a.qty), 0),
                      @dTempap = ISNULL(SUM(a.costtotal), 0)
              FROM    DlyData a
              LEFT JOIN dbo.DlyNdx c ON a.Vchcode = c.Vchcode
              WHERE   --[date] >= @enddate 
                      CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND a.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END >= @enddate 
                      AND a.RedOld = 'F'
                      AND EXISTS ( SELECT 1
                                   FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid) s
                                   WHERE  s.Ktypeid = a.Ktypeid )
                      AND ptypeid = @szPtypeid
                      AND pdetail <> 2
                      AND a.Vchtype NOT IN ('73', '89')
                                                                             
              SELECT  @dQty = ISNULL(@dQTy, 0) - ISNULL(@dTempar, 0)
              SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)
            END
        END
      ELSE 
        IF @szKtypeid <> '99999' 
          BEGIN
            IF @nPSon > 0 
              BEGIN
                SELECT  @dQty = ISNULL(SUM(qty), 0),
                        @dTotal = ISNULL(SUM(total), 0)
                FROM    goodsstocks a
                INNER JOIN Ptype p
                ON      a.PtypeId = p.TypeID
                WHERE   LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                        AND EXISTS ( SELECT 1
                                     FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                     WHERE  Ktypeid = a.Ktypeid )
                        AND p.Stop IN (CASE @IsStop
                                         WHEN 0 THEN p.stop
                                         ELSE 0
                                       END)--是否包含停用商品
                                                                                
                SELECT  @dTempar = ISNULL(SUM(a.qty), 0),
                        @dTempap = ISNULL(SUM(a.costtotal), 0)
                FROM    DlyData a
                LEFT JOIN dbo.DlyNdx c ON a.Vchcode = c.Vchcode
                INNER JOIN Ptype p
                ON      a.PtypeId = p.TypeID
                WHERE   --[date] >= @enddate 
                        CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND a.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END >= @enddate 
                        AND a.RedOld = 'F'
                        AND EXISTS ( SELECT 1
                                     FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                     WHERE  Ktypeid = a.Ktypeid )
                        AND LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                        AND pdetail <> 2
                        AND a.Vchtype NOT IN ('73', '89')
                        AND p.Stop IN (CASE @IsStop
                                         WHEN 0 THEN p.stop
                                         ELSE 0
                                       END)--是否包含停用商品

                SELECT  @dQty = ISNULL(@dQTy, 0) - ISNULL(@dTempar, 0)
                SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)
              END
            ELSE 
              BEGIN
                SELECT  @dQty = ISNULL(SUM(qty), 0),
                        @dTotal = ISNULL(SUM(total), 0)
                FROM    goodsstocks a
                WHERE   ptypeid = @szPtypeid
                        AND EXISTS ( SELECT 1
                                     FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                     WHERE  Ktypeid = a.Ktypeid )
                                                                                        
                SELECT  @dTempar = ISNULL(SUM(a.qty), 0),
                        @dTempap = ISNULL(SUM(a.costtotal), 0)
                FROM    DlyData a
                LEFT JOIN dbo.DlyNdx c ON a.Vchcode = c.Vchcode
                WHERE   --[date] >= @enddate 
                        CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND a.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END >= @enddate 
                        AND a.RedOld = 'F'
                        AND ptypeid = @szPtypeid
                        AND pdetail <> 2
                        AND a.Vchtype NOT IN ('73', '89')
                        AND EXISTS ( SELECT 1
                                     FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                     WHERE  Ktypeid = a.Ktypeid )
                                            
                SELECT  @dQty = ISNULL(@dQTy, 0) - ISNULL(@dTempar, 0)
                SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)
              END
          END
        ELSE 
          IF @szKtypeid = '99999' 
            BEGIN
              IF @nPSon > 0 
                BEGIN

                  SELECT  @dQty = ISNULL(SUM(qty), 0),
                          @dTotal = ISNULL(SUM(total), 0)
                  FROM    goodsstocks a
                  INNER JOIN Ptype p
                  ON      a.PtypeId = p.TypeID
                  WHERE   EXISTS ( SELECT 1
                                   FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                   WHERE  Ktypeid = a.Ktypeid )
                          AND LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                          AND p.Stop IN (CASE @IsStop
                                           WHEN 0 THEN p.stop
                                           ELSE 0
                                         END)--是否包含停用商品
                                                
                  SELECT  @dTempar = ISNULL(SUM(a.qty), 0),
                          @dTempap = ISNULL(SUM(a.costtotal), 0)
                  FROM    DlyData a
                  LEFT JOIN dbo.DlyNdx c ON a.Vchcode = c.Vchcode
                  INNER JOIN Ptype p
                  ON      a.PtypeId = p.TypeID
                  WHERE   --[date] >= @enddate 
                          CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND a.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END >= @enddate 
                          AND a.RedOld = 'F'
                          AND EXISTS ( SELECT 1
                                       FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                       WHERE  Ktypeid = a.Ktypeid )
                          AND LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                          AND pdetail <> 2
                          AND a.Vchtype NOT IN ('73', '89')
                          AND p.Stop IN (CASE @IsStop
                                           WHEN 0 THEN p.stop
                                           ELSE 0
                                         END)--是否包含停用商品
                                                
                  SELECT  @dQty = ISNULL(@dQTy, 0) - ISNULL(@dTempar, 0)
                  SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)
                END
              ELSE 
                BEGIN

                  SELECT  @dQty = ISNULL(SUM(qty), 0),
                          @dTotal = ISNULL(SUM(total), 0)
                  FROM    goodsstocks a
                  WHERE   EXISTS ( SELECT 1
                                   FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                   WHERE  Ktypeid = a.Ktypeid )
                          AND ptypeid = @szPtypeid  
                                                                                                
                  SELECT  @dTempar = ISNULL(SUM(a.qty), 0),
                          @dTempap = ISNULL(SUM(a.costtotal), 0)
                  FROM    DlyData a
                  LEFT JOIN dbo.DlyNdx c ON a.Vchcode = c.Vchcode
                  WHERE   --[date] >= @enddate 
                          CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND a.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END >= @enddate 
                          AND a.RedOld = 'F'
                          AND EXISTS ( SELECT 1
                                       FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                       WHERE  Ktypeid = a.Ktypeid )
                          AND ptypeid = @szPtypeid
                          AND pdetail <> 2
                          AND a.Vchtype NOT IN ('73', '89')
                                                                                                
                  SELECT  @dQty = ISNULL(@dQTy, 0) - ISNULL(@dTempar, 0)
                  SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)              
                END
            END
      RETURN 0	
    END
  ELSE 
    IF @szSelect = 'atype' 
      BEGIN
        SELECT  @dTotal = ISNULL(SUM(total + TTL00), 0)
        FROM    atype
        WHERE   EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangeBCList(@OperatorId, @BranchId)
                         WHERE  BranchID = atype.branchid )
                AND LEFT(typeid, LEN(@szatypeid)) = @szAtypeID
                            
        SELECT  @dTempar = ISNULL(SUM(total), 0)
        FROM    dlya
        WHERE   EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangeBCList(@OperatorId, @BranchId)
                         WHERE  BranchID = dlya.branchid )
                AND [date] >= @enddate
                AND LEFT(atypeid, LEN(@szatypeid)) = @szAtypeid
                 AND RedOld = 'F'
                            
        SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempar, 0)
        SELECT  @dQty = ISNULL(@dTotal, 0)
        RETURN 0
      END
    ELSE 
      IF @szSelect = 'employee' 
        BEGIN  
          SELECT  @dTotal = ISNULL(SUM([total]), 0)
          FROM    dlya
          WHERE   [etypeid] = @szEtypeid AND RedOld = 'F'
                  AND [atypeid] = @szAtypeid
                  AND [btypeid] LIKE @szBtypeid + '%'
          SELECT  @dTempar = ISNULL(SUM([total]), 0)
          FROM    dlya
          WHERE   [etypeid] = @szEtypeid AND RedOld = 'F'
                  AND [atypeid] = '0000200001'
                  AND [btypeid] LIKE @szBtypeid + '%'
          SELECT  @dTotal = @dTotal - @dTempar
          SELECT  @dTempar = ISNULL(SUM([total]), 0)
          FROM    dlya
          WHERE   [etypeid] = @szEtypeid AND RedOld = 'F'
                  AND [atypeid] = @szAtypeid
                  AND [btypeid] LIKE @szBtypeid + '%'
                  AND [date] > @Enddate
          SELECT  @dTotal = @dTotal - @dTempar
          SELECT  @dTempar = ISNULL(SUM([total]), 0)
          FROM    dlya
          WHERE   [etypeid] = @szEtypeid AND RedOld = 'F'
                  AND [atypeid] = '0000200001'
                  AND [btypeid] LIKE @szBtypeid + '%'
                  AND [date] > @Enddate
          SELECT  @dTotal = ISNULL(@dTotal, 0) + ISNULL(@dTempar, 0)
          SELECT  @dQty = ISNULL(@dTotal, 0)
          RETURN 0

        END      
      ELSE 
        IF @szSelect = 'send' 
          BEGIN
            SELECT  @dTotal = ISNULL(SUM(tax_total), 0)
            FROM    DlyData
            WHERE   btypeid = @szBtypeid AND RedOld = 'F'
                    AND vchtype IN (23, 29)
                    AND pdetail <> 2
            SELECT  @dQty = ISNULL(SUM(TOTAL), 0)
            FROM    dlya
            WHERE   btypeid = @szBtypeid AND RedOld = 'F'
                    AND vchtype = 24
                    AND (atypeid LIKE '0000100003%'
                         OR atypeid LIKE '0000100004%')
            SELECT  @dTotal = -1 * @dTotal - @dQty
            SELECT  @dQty = ISNULL(SUM(taxtotal), 0)
            FROM    inicommission
            WHERE   btypeid = @szBtypeid
                    AND type = 4 
            SELECT  @dTotal = @dTotal + @dQty
            SELECT  @dQty = ISNULL(SUM(tax_total), 0)
            FROM    DlyData
            WHERE   btypeid = @szBtypeid AND RedOld = 'F'
                    AND vchtype = 52
            SELECT  @dTotal = ISNULL(@dTotal, 0) + ISNULL(@dQty, 0)
            SELECT  @dQty = ISNULL(@dTotal, 0)
          END
        ELSE 
          IF @szSelect = 'commission'  --委托发货
            BEGIN
              SELECT  @dQty = ISNULL(SUM(Tax_total), 0)
              FROM    DlyData
              WHERE   btypeid LIKE @szBtypeid + '%' AND RedOld = 'F'
                      AND vchtype IN (30, 25, 50)
                      AND pdetail = 2
                      AND [date] <= @EndDate  
				--结算
              SELECT  @dTotal = ISNULL(SUM(Tax_total), 0)
              FROM    DlyData
              WHERE   btypeid LIKE @szBtypeid + '%' AND RedOld = 'F'
                      AND vchtype = 26
                      AND [date] <= @enddate    
              SELECT  @dTotal = @dQty + @dTotal
				--期初
              SELECT  @dQty = ISNULL(SUM(total), 0)
              FROM    iniCommission
              WHERE   btypeid LIKE @szBtypeid + '%'
                      AND type = 1
              SELECT  @dTotal = ISNULL(@dQty, 0) + ISNULL(@dTotal, 0)
              SELECT  @dQty = ISNULL(@dTotal, 0)
            END
          ELSE 
            IF @szSelect = 'recommission' --受托结算
              BEGIN                
                SELECT  @dQty = ISNULL(SUM(Tax_total), 0)
                FROM    DlyData
                WHERE   btypeid LIKE @szBtypeid + '%' AND RedOld = 'F'
                        AND vchtype IN (31, 27, 51)
                        AND pdetail = 2
                        AND [date] <= @EndDate  

					--结算
                SELECT  @dTotal = ISNULL(SUM(Tax_total), 0)
                FROM    DlyData
                WHERE   btypeid LIKE @szBtypeid + '%' AND RedOld = 'F'
                        AND vchtype = 28
                        AND [date] <= @enddate    
                SELECT  @dTotal = @dQty + @dTotal
					--期初
                SELECT  @dQty = ISNULL(SUM(Taxtotal), 0)
                FROM    iniCommission
                WHERE   btypeid LIKE @szBtypeid + '%'
                        AND type = 5
                SELECT  @dTotal = ISNULL(@dQty, 0) + ISNULL(@dTotal, 0)
                SELECT  @dQty = ISNULL(@dTotal, 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].[FZGetStockInOut]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FZGetStockInOut]
GO


CREATE procedure FZGetStockInOut
(
	@PtypeId varchar(50),
	@BranchIdList varchar(8000),
	@KtypeIdList varchar(8000),
	@DateBegin varchar(15),
	@DateEnd varchar(15),
	@Mode Integer = 0,
	@ColorId Integer = -1,
	@SizeId Integer = -1,
	@attrib1 Integer = -1,
	@attrib2 Integer = -1,
	@attrib3 Integer = -1,
	@attrib4 Integer = -1,
	@attrib5 Integer = -1,
	@attrib6 Integer = -1,
	@attrib7 Integer = -1,
	@attrib8 Integer = -1,
	@attribTypeid1 Integer = -1,
	@attribTypeid2 Integer = -1,
	@attribTypeid3 Integer = -1,
	@attribTypeid4 Integer = -1,
	@attribTypeid5 Integer = -1,
	@attribTypeid6 Integer = -1,
	@attribTypeid7 Integer = -1,
	@attribTypeid8 Integer = -1,
	@ShowNoInOut Integer = -1,
	@OperatorId	VARCHAR(50)
)
as
	if @PtypeId = '00000' set @PtypeID = ''
	declare @PtypeIdLength integer
	set @PtypeIdLength = Len(@PtypeId) + 5
	if object_id('tempdb..#KtypeID') is not null drop table #KtypeID 
	create table #KtypeID  (KtypeId varchar(50), KID  [int] IDENTITY(1,1) )      
	Insert #KtypeID select KtypeId from FN_GetStockListOfBranch(@OperatorId,@BranchIdList,@KtypeIdList)
	if @Mode = 0 
	begin
		select Left(PtypeId ,@PtypeIdLength) as PtypeId ,KtypeId ,sum(QcQty) as QCQty, abs(sum(InQty)) As InQty, abs(sum(OutQty)) as OutQty, sum(QMQty) as QMQty from
		(
		select a.PtypeId,a.KtypeId,b.ColorId,
		       b.SizeId, 0 as QCQty, b.Qty as InQty ,
		       0 as OutQty ,0 as QMQty 
		from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder 
		LEFT JOIN dbo.DlyNdx c ON a.vchcode = c.Vchcode 
		where a.billtype IN (1,2,3,8) and b.Qty > 0 
		--and date >= @DateBegin and Date <= @DateEnd  
		AND CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END BETWEEN @DateBegin AND @DateEnd
		and Left(a.PtypeId,Len(@PtypeID)) = @PtypeId and a.KtypeId in (select kk.KtypeId from #KtypeID kk) and a.RedOld = 'F'
		union all
		select a.PtypeId,a.KtypeId,b.ColorId,b.SizeId,0 as QCQty,
		       0 as InQty ,b.Qty as OutQty ,0 as QMQty 
		from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder 
		LEFT JOIN dbo.DlyNdx c ON a.vchcode = c.Vchcode 
		where a.billtype IN (1,2,3,8) and  b.Qty < 0 
		--and date >= @DateBegin and Date <= @DateEnd 
		AND CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END BETWEEN @DateBegin AND @DateEnd
		and Left(a.PtypeId,Len(@PtypeID)) = @PtypeId and a.KtypeId in (select kk.KtypeId from #KtypeID kk) and a.RedOld = 'F'
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, b.Qty as QCQty ,0 as InQty, 0 as OutQty, 0 as QMQty from inigoodsstocks a left join inigoodsdetail b on a.orderid = b.orderid where Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) 
		union all
		select a.PtypeId,a.KtypeId,b.ColorId,b.SizeId, b.Qty as QCQty, 0 as Inqty, 0 as OutQty, 0 as QMQty 
		from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder 
		LEFT JOIN dbo.DlyNdx c ON a.vchcode = c.Vchcode 
		where a.billtype IN (1,2,3,8) 
		--and Date < @DateBegin 
		AND CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END < @DateBegin 
		and Left(a.PtypeId,Len(@PtypeID)) = @PtypeId 
		and a.KtypeId in (select kk.KtypeId from #KtypeID kk) and a.RedOld = 'F'
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, 0 as QCQty, 0 as InQty, 0 as OutQty, b.Qty as QMQty from goodsstocks a left join goodsstockdetail b on a.orderid = b.orderid where Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) 
		union all
		select a.PtypeId,a.KtypeId,b.ColorId,b.SizeId, 0 as QCQty, 0 as Inqty, 0 as OutQty, -b.Qty as QMQty 
		from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder 
		LEFT JOIN dbo.DlyNdx c ON a.vchcode = c.Vchcode 
		where a.billtype IN (1,2,3,8) 
		--and Date > @DateEnd 
		AND CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END > @DateEnd 
		and Left(a.PtypeId,Len(@PtypeID)) = @PtypeId 
		and a.KtypeId in (select kk.KtypeId from #KtypeID kk) and a.RedOld = 'F'
		) a
		WHERE PtypeId IN (SELECT typeid FROM FN_GetPowerRangePList(@OperatorId,''))--操作员商品权限范围
		group by Left(PtypeId ,@PtypeIdLength), KtypeID		
		order by Left(PtypeId ,@PtypeIdLength),KtypeId
	end
	if @Mode = 1 
	begin
		select a.PtypeId ,KtypeId ,sum(QcQty) as QCQty, abs(sum(InQty)) As InQty, abs(sum(OutQty)) as OutQty, sum(QMQty) as QMQty, 
		right('00000'+cast(isnull(a.ColorId,-1) as varchar),5) as PCTypeid,right('00000'+cast(isnull(a.Sizeid,-1) as varchar),5) as PSTypeid ,
		(SELECT TOP 1 [Order] FROM [dbo].[Size] si WHERE si.SizeId = a.SizeID ) AS psOrder 
		from
		(
		select a.PtypeId,a.KtypeId,b.ColorId,b.SizeId, 0 as QCQty, b.Qty as InQty ,0 as OutQty ,0 as QMQty 
		from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder 
		LEFT JOIN dbo.DlyNdx c ON a.vchcode = c.Vchcode 
		where a.billtype IN (1,2,3,8) and b.Qty > 0 
		--and date >= @DateBegin and Date <= @DateEnd  
		AND CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END BETWEEN @DateBegin AND @DateEnd
		and Left(a.PtypeId,Len(@PtypeID)) = @PtypeId 
		and a.KtypeId in (select kk.KtypeId from #KtypeID kk) and a.RedOld = 'F'
		union all
		select a.PtypeId,a.KtypeId,b.ColorId,b.SizeId,0 as QCQty,0 as InQty ,b.Qty as OutQty ,0 as QMQty 
		from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder 
		LEFT JOIN dbo.DlyNdx c ON a.vchcode = c.Vchcode 
		where a.billtype IN (1,2,3,8) and  b.Qty < 0 
		--and date >= @DateBegin and Date <= @DateEnd 
		AND CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END BETWEEN @DateBegin AND @DateEnd
		and Left(a.PtypeId,Len(@PtypeID)) = @PtypeId 
		and a.KtypeId in (select kk.KtypeId from #KtypeID kk) and a.RedOld = 'F'
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, b.Qty as QCQty ,0 as InQty, 0 as OutQty, 0 as QMQty from inigoodsstocks a left join inigoodsdetail b on a.orderid = b.orderid where Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) 
		union all
		select a.PtypeId,a.KtypeId,b.ColorId,b.SizeId, b.Qty as QCQty, 0 as Inqty, 0 as OutQty, 0 as QMQty 
		from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder 
		LEFT JOIN dbo.DlyNdx c ON a.vchcode = c.Vchcode 
		where a.billtype IN (1,2,3,8) 
		--and Date < @DateBegin 
		AND CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END < @DateBegin 
		and Left(a.PtypeId,Len(@PtypeID)) = @PtypeId 
		and a.KtypeId in (select kk.KtypeId from #KtypeID kk) and a.RedOld = 'F'
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, 0 as QCQty, 0 as InQty, 0 as OutQty, b.Qty as QMQty from goodsstocks a left join goodsstockdetail b on a.orderid = b.orderid where Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) 
		union all
		select a.PtypeId,a.KtypeId,b.ColorId,b.SizeId, 0 as QCQty, 0 as Inqty, 0 as OutQty, -b.Qty as QMQty 
		from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder 
		LEFT JOIN dbo.DlyNdx c ON a.vchcode = c.Vchcode 
		where a.billtype IN (1,2,3,8) 
		--and Date > @DateEnd 
		AND CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END > @DateEnd 
		and Left(a.PtypeId,Len(@PtypeID)) = @PtypeId 
		and a.KtypeId in (select kk.KtypeId from #KtypeID kk) and a.RedOld = 'F'
  		) a 
                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b 
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid1) ls1
                  on  @attrib1 <> -1 and ls1.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b 
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid2) ls2
                  on  @attrib2 <> -1 and ls2.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid3) ls3
                  on  @attrib3 <> -1 and ls3.ptypeid = a.Ptypeid
                 
                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid4) ls4
                  on  @attrib4 <> -1 and ls4.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid5) ls5
                  on  @attrib5 <> -1 and ls5.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid6) ls6
                  on  @attrib6 <> -1 and ls6.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid7) ls7
                  on  @attrib7 <> -1 and ls7.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid8) ls8
                  on  @attrib8 <> -1 and ls8.ptypeid = a.Ptypeid
                      Where
				Colorid = case @ColorId when -1 then ColorId else @ColorId end and
				SizeId = case @SizeId when -1 then SizeId else @SizeId end and
        isnull(ls1.attributeid,-1) =  case when @attrib1 = -1 then isnull(ls1.attributeid,-1) else @attrib1 end
        and isnull(ls2.attributeid,-1) =  case when @attrib2 = -1 then isnull(ls2.attributeid,-1) else @attrib2 end
        and isnull(ls3.attributeid,-1) =  case when @attrib3 = -1 then isnull(ls3.attributeid,-1) else @attrib3 end
        and isnull(ls4.attributeid,-1) =  case when @attrib4 = -1 then isnull(ls4.attributeid,-1) else @attrib4 end
        and isnull(ls5.attributeid,-1) =  case when @attrib5 = -1 then isnull(ls5.attributeid,-1) else @attrib5 end
        and isnull(ls6.attributeid,-1) =  case when @attrib6 = -1 then isnull(ls6.attributeid,-1) else @attrib6 end
        and isnull(ls7.attributeid,-1) =  case when @attrib7 = -1 then isnull(ls7.attributeid,-1) else @attrib7 end
        and isnull(ls8.attributeid,-1) =  case when @attrib8 = -1 then isnull(ls8.attributeid,-1) else @attrib8 end
	and a.PtypeId IN (SELECT typeid FROM FN_GetPowerRangePList(@OperatorId,''))--操作员商品权限范围
				group by a.PtypeId, KtypeID,a.ColorId,a.SizeId 
				having case @ShowNoInOut when 1 then 1 else abs(sum(InQty)) end> 0 or case @ShowNoInOut when 1 then 1 else abs(sum(OutQty)) end> 0	
				order by a.PtypeId,a.colorId,psOrder,a.sizeId,KtypeId
	end	 
	if @Mode = 2 
	begin
		select a.PtypeId ,KtypeId ,sum(QcQty) as QCQty, abs(sum(InQty)) As InQty, abs(sum(OutQty)) as OutQty, sum(QMQty) as QMQty from
		(
		select a.PtypeId,a.KtypeId,b.ColorId,b.SizeId, 0 as QCQty, b.Qty as InQty ,0 as OutQty ,0 as QMQty 
		from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder 
		LEFT JOIN dbo.DlyNdx c ON a.vchcode = c.Vchcode 
		where a.billtype IN (1,2,3,8) and b.Qty > 0 
		--and date >= @DateBegin and Date <= @DateEnd  
		AND CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END BETWEEN @DateBegin AND @DateEnd
		and Left(a.PtypeId,Len(@PtypeID)) = @PtypeId 
		and a.KtypeId in (select kk.KtypeId from #KtypeID kk) and a.RedOld = 'F'
		union all
		select a.PtypeId,a.KtypeId,b.ColorId,b.SizeId,0 as QCQty,0 as InQty ,b.Qty as OutQty ,0 as QMQty 
		from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder 
		LEFT JOIN dbo.DlyNdx c ON a.vchcode = c.Vchcode 
		where a.billtype IN (1,2,3,8) and  b.Qty < 0 
		--and date >= @DateBegin and Date <= @DateEnd 
		AND CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END BETWEEN @DateBegin AND @DateEnd
		and Left(a.PtypeId,Len(@PtypeID)) = @PtypeId 
		and a.KtypeId in (select kk.KtypeId from #KtypeID kk) and a.RedOld = 'F'
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, b.Qty as QCQty ,0 as InQty, 0 as OutQty, 0 as QMQty from inigoodsstocks a left join inigoodsdetail b on a.orderid = b.orderid where Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) 
		union all
		select a.PtypeId,a.KtypeId,b.ColorId,b.SizeId, b.Qty as QCQty, 0 as Inqty, 0 as OutQty, 0 as QMQty 
		from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder 
		LEFT JOIN dbo.DlyNdx c ON a.vchcode = c.Vchcode 
		where a.billtype IN (1,2,3,8) 
		--and Date < @DateBegin 
		AND CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END < @DateBegin 
		and Left(a.PtypeId,Len(@PtypeID)) = @PtypeId 
		and a.KtypeId in (select kk.KtypeId from #KtypeID kk) and a.RedOld = 'F'
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, 0 as QCQty, 0 as InQty, 0 as OutQty, b.Qty as QMQty from goodsstocks a left join goodsstockdetail b on a.orderid = b.orderid where Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) 
		union all
		select a.PtypeId,a.KtypeId,b.ColorId,b.SizeId, 0 as QCQty, 0 as Inqty, 0 as OutQty, -b.Qty as QMQty 
		from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder 
		LEFT JOIN dbo.DlyNdx c ON a.vchcode = c.Vchcode 
		where a.billtype IN (1,2,3,8) 
		--and Date > @DateEnd 
		AND CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END > @DateEnd 
		and Left(a.PtypeId,Len(@PtypeID)) = @PtypeId 
		and a.KtypeId in (select kk.KtypeId from #KtypeID kk) and a.RedOld = 'F'
  		) a 
                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b 
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid1) ls1
                  on  @attrib1 <> -1 and ls1.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b 
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid2) ls2
                  on  @attrib2 <> -1 and ls2.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid3) ls3
                  on  @attrib3 <> -1 and ls3.ptypeid = a.Ptypeid
                 
                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid4) ls4
                  on  @attrib4 <> -1 and ls4.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid5) ls5
                  on  @attrib5 <> -1 and ls5.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid6) ls6
                  on  @attrib6 <> -1 and ls6.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid7) ls7
                  on  @attrib7 <> -1 and ls7.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid8) ls8
                  on  @attrib8 <> -1 and ls8.ptypeid = a.Ptypeid
                      Where
        isnull(ls1.attributeid,-1) =  case when @attrib1 = -1 then isnull(ls1.attributeid,-1) else @attrib1 end
        and isnull(ls2.attributeid,-1) =  case when @attrib2 = -1 then isnull(ls2.attributeid,-1) else @attrib2 end
        and isnull(ls3.attributeid,-1) =  case when @attrib3 = -1 then isnull(ls3.attributeid,-1) else @attrib3 end
        and isnull(ls4.attributeid,-1) =  case when @attrib4 = -1 then isnull(ls4.attributeid,-1) else @attrib4 end
        and isnull(ls5.attributeid,-1) =  case when @attrib5 = -1 then isnull(ls5.attributeid,-1) else @attrib5 end
        and isnull(ls6.attributeid,-1) =  case when @attrib6 = -1 then isnull(ls6.attributeid,-1) else @attrib6 end
        and isnull(ls7.attributeid,-1) =  case when @attrib7 = -1 then isnull(ls7.attributeid,-1) else @attrib7 end
        and isnull(ls8.attributeid,-1) =  case when @attrib8 = -1 then isnull(ls8.attributeid,-1) else @attrib8 end
	and a.PtypeId IN (SELECT typeid FROM FN_GetPowerRangePList(@OperatorId,''))--操作员商品权限范围
				group by a.PtypeId,KtypeID 
				order by a.PtypeId,KtypeId
	end	 
  	drop table #KtypeID





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].[FZMXZBGetAllList]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZMXZBGetAllList]
GO


--  ********************************************************************************************
--  ||                                                                                        
--  ||   过程名称： F_MXZB_GetAllList                            
--  ||   过程功能：得到各个科目的明细（查询明细账本用）
--  ||=========================================================================================
--  ||   参数说明：  参数名称         类型                    意义                     输入输出
--  ||            -----------------------------------------------------------------------------
--  ||          得到各个科目的明细
--  || 		@cMode		varchar（5）
--  || 	                                        'A'	科目明细
--  || 	                                        'P'	商品明细
--  ||  	                                'B'	应收应付明细
--  ||  	                                'H'	换货单据明细
--  ||  	                                'S'	销售单据明细
--  ||  	                                'I'	进货单据明细
--  ||						'O'     退货单据明细
--  ||						'D'     加盟店配货订单明细
--  ||						'Q'     自营店配货订单明细
--  || 						'J'	加盟店零售明细
--  ||						'Shop'  商场专柜销售统计
--  || 						'Y'	销售优惠明细
--  || 						'YKCZKB'库存状况明细单据'
--  ||  	@szAtypeId	varchar(50),            会计科目编号
--  ||  	@szPtypeId	varchar(50),            商品编码
--  ||  	@szBtypeId	varchar(50),            往来单位编码
--  ||  	@szEtypeId	varchar(50),            职员编码
--  ||  	@szKtypeId	varchar(50),            仓库编码
--  ||  	@szPeriod	varchar(10),            会计期间
--  ||  	@szBeginData	varchar(10),            开始日期
--  ||  	@szEndData	varchar(10)             结束日期
--  ||  	@ifjs           varvhar(10)             0：统计未结算的，1：统计已经结算的，''：统计所有
--  ||=========================================================================================   
--  ||  返回值：  值                          说明
--  || --------------------------------------------------------------------------------------- 	 
--  ||  	 	返回 0		是成功
--  ||  	 	返回 -101	是没有数据
--  ||  	 	返回 -102	是查询失败
--  ||=========================================================================================   
 CREATE          PROCEDURE FZMXZBGetAllList
    (
      @cMode VARCHAR(30),
      @szAtypeId VARCHAR(50),
      @szPtypeId VARCHAR(50),
      @szBtypeId VARCHAR(50),
      @szEtypeId VARCHAR(50),
      @szKtypeId VARCHAR(2000),   --有仓库组控制，可能传入多个仓库ID的字符创
      @szPeriod VARCHAR(10),
      @szBeginData VARCHAR(10),
      @szEndData VARCHAR(10),
      @ifjs VARCHAR(1),
      @ifstop VARCHAR(1),
      @SaleTraitname VARCHAR(1000) = '',
      @deptid VARCHAR(50),
      @CustType VARCHAR(10) = '',
      @Branchid VARCHAR(2000) = '',
      @OperatorId VARCHAR(50),
      @IsStop BIT = 0,--是否包含停用商品 0：包含  1：不包含
      @IncludeYSYF VARCHAR(1) = 0 --是否包含预收预付
    )
 AS 
    SET nocount ON
    DECLARE @sql VARCHAR(8000)
    DECLARE @ROOT_ID VARCHAR(50)
    DECLARE @GOOD_ID VARCHAR(50)
    DECLARE @CASH_ID VARCHAR(50)
    DECLARE @CASH_BANK_ID VARCHAR(50)
    DECLARE @GETMONEYBILL INT
    DECLARE @SALEBILL INT
    DECLARE @SALEBACKBILL INT
    DECLARE @LENDSALEBILL INT 
    DECLARE @BUYBILL INT 
    DECLARE @BUYBACKBILL INT 
    DECLARE @BORROWBUYBILL INT 
    DECLARE @ALL_QTY NUMERIC(24, 10)
    DECLARE @ALL_TOTAL NUMERIC(24, 10)
    DECLARE @AP_ID VARCHAR(50)
    DECLARE @AR_ID VARCHAR(50)
    DECLARE @nPSonnum INT
    DECLARE @nBSonnum INT 
    DECLARE @nESonnum INT
    DECLARE @nKSonnum INT
    DECLARE @BORROW_KTYPE VARCHAR(10)
    DECLARE @LEND_KTYPE VARCHAR(10)
    DECLARE @where VARCHAR(100)  
    DECLARE @RECOMMISSION_PRICE_VCHTYPE INT
    DECLARE @COMMISSION_PRICE_VCHTYPE INT
    DECLARE @RECOMMISSION_JS_VCHTYPE INT
    DECLARE @COMMISSION_JS_VCHTYPE INT
    DECLARE @Pdetail INT
    DECLARE @RECOMMISSION_VCHTYPE INT
    DECLARE @COMMISSION_VCHTYPE INT
    DECLARE @RECOMMISSION_BACK_VCHTYPE INT
    DECLARE @COMMISSION_BACK_VCHTYPE INT
    SELECT  @Pdetail = 2
    SELECT  @RECOMMISSION_PRICE_VCHTYPE = 51--受托调价
    SELECT  @COMMISSION_PRICE_VCHTYPE = 50--委托调价
    SELECT  @RECOMMISSION_JS_VCHTYPE = 28--受托收货结算
    SELECT  @COMMISSION_JS_VCHTYPE = 26--委托结算
    SELECT  @RECOMMISSION_VCHTYPE = 27--受托收货
    SELECT  @COMMISSION_VCHTYPE = 25--委托代销
    SELECT  @RECOMMISSION_BACK_VCHTYPE = 31--受托收货退货
    SELECT  @COMMISSION_BACK_VCHTYPE = 30--委托退货单
    SELECT  @where = ''
    SELECT  @ROOT_ID = '00000'
    SELECT  @GOOD_ID = '0000100001'
    SELECT  @CASH_ID = '0000100003'
    SELECT  @CASH_BANK_ID = '0000100004'
    SELECT  @AR_ID = '0000100005'
    SELECT  @AP_ID = '0000200001'
    SELECT  @GETMONEYBILL = 4
    SELECT  @SALEBILL = 11
    SELECT  @SALEBACKBILL = 45
    SELECT  @LENDSALEBILL = 89
    SELECT  @BUYBILL = 34
    SELECT  @BUYBACKBILL = 6
    SELECT  @BORROWBUYBILL = 73
    SELECT  @nPSonnum = [sonnum]
    FROM    Ptype
    WHERE   [typeid] = @szPtypeId
    SELECT  @nBSonnum = [sonnum]
    FROM    btype
    WHERE   [typeid] = @szBtypeId
    SELECT  @nESonnum = [sonnum]
    FROM    employee
    WHERE   [typeid] = @szEtypeId
    SELECT  @nKSonnum = [sonnum]
    FROM    stock
    WHERE   [typeid] = @szKtypeId
    IF @nPSonnum = NULL 
        SELECT  @nPSonnum = 0
    IF @nBSonnum = NULL 
        SELECT  @nBSonnum = 0
    IF @nESonnum = NULL 
        SELECT  @nESonnum = 0
    IF @nKSonnum = NULL 
        SELECT  @nKSonnum = 0
    SELECT  @BORROW_KTYPE = '9999999998'
    SELECT  @LEND_KTYPE = '9999999999'
    DECLARE @Business_EXPENSE_ID VARCHAR(50)   
    SELECT  @Business_EXPENSE_ID = '0000400003' 
	
	--新增存储过程 GetDig，用来取小数配置。以后所有报表存储过程对小数位的取舍用以下方式。
    DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
    EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
	
    IF @SaleTraitname = '' 
        SET @SaleTraitname = '全部'
    IF @ifjs <> '' 
        SELECT  @where = @where + '  and ifjs = (case ' + @ifjs
                + ' when 0 then ifjs else ' + @ifjs + ' end) ' 	
    IF ( @szAtypeId = '' )
        OR ( @szAtypeId = @ROOT_ID ) 
        SELECT  @szAtypeId = '%%'
    IF ( @szPtypeId = '' )
        OR ( @szPtypeId = @ROOT_ID ) 
        SELECT  @szPtypeId = '%%'
    IF ( @szBtypeId = '' )
        OR ( @szBtypeId = @ROOT_ID ) 
        SELECT  @szBtypeId = '%%'
    IF @deptid = NULL 
        SELECT  @deptid = ''
	--if @cMode in( 'G','B','E','BK1')		
	--begin
    IF ( @szEtypeId = '' ) 
        SELECT  @szEtypeId = '%%' --职员费用明细帐，为空时是所有职员
	--end
	--else
	--begin
		--if (@szEtypeId='')  Select @szEtypeId='%%' -- 其他情况为空或者为‘00000’是所有职员
	--end
    IF @ifstop = '' 
        SELECT  @ifstop = 1
    IF ( @szKtypeId = '' )
        OR ( @szKtypeId = @ROOT_ID ) 
        SELECT  @szKtypeId = '%%'
	--if not exists(Select * From Dlyndx Where [date]>=@szBeginData and [date]<=@szEndData) and upper(@cMode)<>'A'  goto error2
	
    IF @cMode = 'A' 
        GOTO GetAtype
    ELSE 
        IF @cMode = 'P' 
            GOTO GetPtype--库存商品明细
        ELSE 
            IF @cMode IN ( 'B', 'BK', 'BK1', 'QueryConBtype', 'QueryBtypeSale' ) 
                GOTO GetBtype --往来单明细
            ELSE 
                IF @cMode = 'E' 
                    GOTO GetEtype --职员明细
                ELSE 
                    IF @cMode = 'I' 
                        GOTO GetBuy --进货明细(包括受托结算)
                    ELSE 
                        IF @cMode = 'IG' GOTO GetBuy1--进货明细(只包含进货和退货)
                        ELSE 
                            IF @cMode = 'S' 
                                GOTO GetSale --销售明细
                            ELSE 
                                IF @cMode = 'J' 
                                    GOTO GetJoinSale --加盟店销售明细
                                ELSE 
                                    IF @cMode = 'D' 
                                        GOTO GetJoinorder --加盟店订单明细
                                    ELSE 
                                        IF @cMode = 'Q' 
                                            GOTO GetBuyorder --自营店订单明细
                                        ELSE 
                                            IF @cMode = 'O' 
                                                GOTO GetBuyback --进货退货明细
                                            ELSE 
                                                IF @cMode = 'H' 
                                                    GOTO GetSaleExchange--销售换货明细
                                                ELSE 
                                                    IF @cMode = 'Y' 
                                                        GOTO GetSalepreferential --优惠统计明细
                                                    ELSE 
                                                        IF @cMode = 'G' 
                                                            GOTO GetExp  --8。
                                                        ELSE 
                                                            IF @cMode = 'JS' GOTO GetJoinStock --加盟店库存明细
                                                            ELSE 
                                                                IF @cMode = 'BO' GOTO GetBuyandback--进货退货分析明细
                                                                ELSE 
                                                                    IF UPPER(@cMode) = 'SELF' 
                                                                        GOTO GetSelf --自营店库存明细
                                                                    ELSE 
                                                                        IF UPPER(@cMode) = 'SHOP' 
                                                                            GOTO GetShop --商场专柜明细
                                                                        ELSE 
                                                                            IF UPPER(@cMode) = 'JOIN' 
                                                                                GOTO GetJoin --加盟店销售统计明细
                                                                            ELSE 
                                                                                IF UPPER(@cMode) = 'TEMP' GOTO GetTemp --取得周转仓库的明细账本
                                                                                ELSE 
                                                                                    IF UPPER(@cMode) = 'LSTJFX' 
                                                                                        GOTO GetRetailSale--零售销售统计
                                                                                    ELSE 
                                                                                        IF UPPER(@cMode) = 'KHXSFX' 
                                                                                            GOTO GetBtypeSaleAnalyse--客户销售分析
                                                                                        ELSE 
                                                                                            IF UPPER(@cMode) = 'YKCZKB' 
                                                                                                GOTO GetStockBillDetail --库存状况单据明细
                                                                                            ELSE 
                                                                                                IF UPPER(@cMode) = 'YKCZKB_JOIN' 
                                                                                                    GOTO GetStockJOINBillDetail 
                                                                                                ELSE 
                                                                                                    IF UPPER(@cMode) = 'SCDZTJ' 
                                                                                                        GOTO getSCDZTJ --商场对账统计

--取得周转仓库的明细账本
    getSCDZTJ:

    SELECT  a.VchCode,
            a.[Date],
            a.Number,
            a.summary,
            a.vchtype,
            a.Redold,
            a.btypeid,
            a.redword,
            ( ISNULL(( SELECT   SUM(CASE atypeid
                                      WHEN '0000200001' THEN -total
                                      ELSE total
                                    END)
                       FROM     dlya
                       WHERE    ( atypeid = '0000200001'
                                  OR atypeid = '0000100005'
                                )
                                AND VchCode = a.VchCode
                     ), 0) ) AS YSHKMoney,
            ( CASE WHEN a.VchType IN ( 36 ) THEN SUM(a.total)
                   ELSE 0
              END ) FyMoney,
            ( CASE WHEN a.vchtype IN ( 4, 66 ) THEN SUM(b.total)
                   ELSE SUM(c.total)
              END ) AS HKMoney,
            ( SELECT    SUM(-SaleMoney)
              FROM      dlydata
              WHERE     vchcode = a.vchcode
                        AND billtype = 2
                        AND usedtype = CASE WHEN vchtype IN ( 222, 224 )
                                            THEN 1
                                            ELSE usedtype
                                       END
            ) AS Total,
            ( SELECT    ROUND(-MarketDiscount1 *CONVERT(NUMERIC(24,10),SUM(SaleMoney)) / 100, @dig_total)
              FROM      dlydata
              WHERE     vchcode = a.vchcode
                        AND billtype = 2
                        AND usedtype = CASE WHEN vchtype IN ( 222, 224 )
                                            THEN 1
                                            ELSE usedtype
                                       END
             GROUP BY MarketDiscount1                         
            ) AS DeductTotal
    FROM    dlyndx a
            LEFT JOIN ( SELECT  VchCode,
                                total
                        FROM    dlya
                        WHERE   vchCode IN ( SELECT vchCode
                                             FROM   dlyndx
                                             WHERE  vchtype IN ( 4, 66 ) )
                                AND usedtype = 1
                                AND Btypeid LIKE @szBtypeId + '%'
                                AND LEFT(btypeid, 5) = '00003'
                      ) b ON b.vchCode = a.VchCode
            LEFT JOIN ( SELECT  VchCode,
                                Total,
                                atypeid
                        FROM    DlyA
                        WHERE   Btypeid LIKE @szBtypeId + '%'
                      ) c ON c.VchCode = a.VchCode
                             AND c.Atypeid = a.Atypeid
    WHERE   a.vchType IN ( 4, 66, 36, 250, 100, 101 )
            AND ( ( a.Btypeid LIKE @szBtypeId + '%' )
                  OR a.vchcode IN ( SELECT  vchCode
                                    FROM    dlya
                                    WHERE   btypeid LIKE @szBtypeId + '%'
                                            AND vchtype = 125
                                            AND ( atypeid = '0000200001'
                                                  OR atypeid = '0000100005'
                                                ) )
                )
            AND a.[Date] >= @szBeginData
            AND a.[Date] <= @szEndData
            AND a.draft = '2'
            AND LEFT(btypeid, 5) = '00003'
    GROUP BY a.VchCode,
            a.btypeid,
            a.[Date],
            a.Number,
            a.VchType,
            a.summary,
            a.vchtype,
            a.Atypeid,
            a.redword,
            a.Redold,
            a.total
    ORDER BY a.[date],
            a.Number,
            a.vchtype DESC
    GOTO Succee

    GetTemp:
    SELECT  dn.date,
            dn.vchtype,
            number,
            dn.summary AS Comment,
            CASE WHEN d.qty <= 0 THEN ABS(ISNULL(d.qty, 0))
                 ELSE 0
            END AS Qtyin,
            CASE WHEN d.qty > 0 THEN ABS(ISNULL(d.qty, 0))
                 ELSE 0
            END AS Qtyout,
            ISNULL(d.qty, 0) AS qty,
            fullname AS pfullname,
            usercode AS pusercode,
            ptypeid,
            usercode,
            ISNULL(d.costTotal, 0) AS total,
            dn.vchcode,
            p.fullname,
            dn.redold,
            d.redword
    FROM    dlydata d,
            dlyndx dn,
            FN_GetPowerRangePList(@OperatorId, '') p
    WHERE   dn.vchcode = d.vchcode
            AND dn.vchtype IN ( 212, 215, 240, 218 )
            AND d.ktypeid = '99999'
            AND dn.date >= @szBeginData
            AND dn.date <= @szEndData
            AND d.ptypeid = p.typeid
            AND p.typeid LIKE @szPtypeId
    UNION ALL
    SELECT  dn.date,
            dn.vchtype,
            number,
            dn.summary AS Comment,
            CASE WHEN d.qty <= 0 THEN ABS(ISNULL(d.qty, 0))
                 ELSE 0
            END AS Qtyin,
            CASE WHEN d.qty > 0 THEN ABS(ISNULL(d.qty, 0))
                 ELSE 0
            END AS Qtyout,
            ISNULL(d.qty, 0) AS qty,
            fullname AS pfullname,
            usercode AS pusercode,
            ptypeid,
            usercode,
            ROUND(ISNULL(d.qty * d.costprice, 0),@dig_total) AS total,
            dn.vchcode,
            p.fullname,
            dn.redold,
            d.redword
    FROM    dlydata d,
            dlyndx dn,
            FN_GetPowerRangePList(@OperatorId, '') p
    WHERE   dn.vchcode = d.vchcode
            AND dn.vchtype = 230
            AND d.Ktypeid = '99999'
            AND dn.date >= @szBeginData
            AND dn.date <= @szEndData
            AND d.ptypeid = p.typeid
            AND p.typeid LIKE @szPtypeId
    ORDER BY dn.vchcode
    GOTO succee
	
--	得到会计科目的明细
    GetAtype:
	
    SELECT  a.[fullname],
            da.[vchcode],
            da.[vchtype],
            ISNULL(da.[total], 0) AS Total,
            CASE WHEN da.total > 0 THEN ISNULL(da.total, 0)
                 ELSE 0
            END AS Increase,
            CASE WHEN da.total < 0 THEN ABS(ISNULL(da.total, 0))
                 ELSE 0
            END AS Reduce,
            da.[date],
            ISNULL(dn.[number], '') AS number,
            ISNULL(dn.[summary], '') AS comment,
            dn.redold,
            da.redword
    FROM    ( SELECT    *
              FROM      atype
              WHERE     [deleted] <> 1
            ) a,
            ( SELECT    *
              FROM      DlyA
              WHERE     @szBeginData <= [date]
                        AND @szEndData >= [date]
            ) da,
            ( SELECT    *
              FROM      DlyNdx
              WHERE     @szBeginData <= [date]
                        AND @szEndData >= [date]
       --                 and 
       --                 (
							--(@szAtypeId='0000100001' AND ((@Branchid='00001' and VchType not IN(212,218)) or (@Branchid<>'00001' )))
							--OR @szAtypeId<>'0000100001'
       --                 )
            ) dn
    WHERE   LEFT(da.[atypeId], LEN(@szAtypeId)) LIKE @szAtypeId
            AND da.[vchcode] = dn.[vchcode]
            AND a.[typeid] = da.[atypeid]
            AND a.BranchID = da.BranchId
           -- AND a.BranchID LIKE @Branchid + '%'
            AND EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangeBCList(@OperatorId, @Branchid) b
                         WHERE  a.branchid = b.branchid )
    UNION ALL
    SELECT  a.[fullname],
            da.[vchcode],
            da.[vchtype],
            ISNULL(da.[total], 0) AS Total,
            CASE WHEN da.total > 0 THEN ISNULL(da.total, 0)
                 ELSE 0
            END AS Increase,
            CASE WHEN da.total < 0 THEN ABS(ISNULL(da.total, 0))
                 ELSE 0
            END AS Reduce,
            da.[date],
            '' AS number,
            '会员卡存储金额' AS comment,
            'F' AS redold,
            da.redword
    FROM    ( SELECT    *
              FROM      atype
              WHERE     [deleted] <> 1
            ) a,
            ( SELECT    *
              FROM      DlyA
              WHERE     @szBeginData <= [date]
                        AND @szEndData >= [date]
            ) da
    WHERE   LEFT(da.[atypeId], LEN(@szAtypeId)) LIKE @szAtypeId
            AND a.[typeid] = da.[atypeid]
            AND da.vchcode = 0
            AND a.BranchID = da.BranchId
          --  AND a.BranchID LIKE @Branchid + '%'
            AND EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangeBCList(@OperatorId, @Branchid) b
                         WHERE  a.branchid = b.branchid )
    ORDER BY da.vchcode
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	--Order by da.[vchcode]
--	得到往来客户的明细

    GetBtype:
--	得到应收应付的明细
    IF @cMode = 'QueryBtypeSale' 
        BEGIN
            SELECT  v.*,
                    atypeid
            FROM    ( SELECT    a.vchcode,
                                a.vchtype,
                                a.atypeid,
                                a.date,
                                b.redold,
                                a.btypeid,
                                b.number,
                                b.summary AS comment,
                                a.total,
                                CASE WHEN a.total > 0 THEN a.total
                                     ELSE 0
                                END AS increase,
                                CASE WHEN a.total < 0 THEN -1 * a.total
                                     ELSE 0
                                END AS reduce,
                                -( a.Total ) AS ReverseTotal,
                                a.redword,
                                b.BranchId
                      FROM      dlyndx b
                                INNER JOIN dlya a ON b.vchcode = a.vchcode
                                LEFT JOIN btype c ON a.btypeid = c.typeid
                      WHERE     @szBeginData <= b.[date]
                                AND @szEndData >= b.[date]
                                AND a.atypeid = @AR_ID
                                AND b.vchtype IN ( 100, 101, 11, 45, 26, 24,
                                                   13, 12, 222, 224, 4, 36, 93,
                                                   115, 66 )
                                AND a.btypeid LIKE @szbtypeid + '%'
                      UNION ALL
                      SELECT    a.vchcode,
                                a.vchtype,
                                a.atypeid,
                                a.date,
                                b.redold,
                                a.btypeid,
                                b.number,
                                b.summary AS comment,
                                -1 * a.total total,
                                CASE WHEN a.total < 0 THEN -1 * a.total
                                     ELSE 0
                                END AS increase,
                                CASE WHEN a.total > 0 THEN a.total
                                     ELSE 0
                                END AS reduce,
                                a.total AS ReverseTotal,
                                a.redword,
                                b.BranchId
                      FROM      dlyndx b
                                INNER JOIN dlya a ON b.vchcode = a.vchcode
                                LEFT JOIN btype c ON a.btypeid = c.typeid
                      WHERE     @szBeginData <= b.[date]
                                AND @szEndData >= b.[date]
                                AND b.vchtype IN ( 100, 101, 11, 45, 26, 24,
                                                   13, 12, 222, 224, 4, 36, 93,
                                                   115, 66 )
                                AND a.atypeid = @AP_ID
                                AND a.btypeid LIKE @szbtypeid + '%'
                      UNION ALL
                      SELECT DISTINCT
                                a.vchcode,
                                a.vchtype,
                                '' AS atypeid,
                                a.date,
                                b.redold,
                                a.btypeid,
                                b.number,
                                b.summary AS comment,
                                0 AS total,
                                0 AS increase,
                                0 AS reduce,
                                0 AS ReverseTotal,
                                a.redword,
                                b.BranchId
                      FROM      dlyndx b
                                INNER JOIN ( SELECT DISTINCT
                                                    btypeid,
                                                    vchcode,
                                                    vchtype,
                                                    [date],
                                                    redword
                                             FROM   dlya
                                             WHERE  vchcode NOT IN (
                                                    SELECT  vchcode
                                                    FROM    dlya
                                                    WHERE   atypeid = '0000100005'
                                                            OR atypeid = '0000200001' )
                                           ) a ON b.vchcode = a.vchcode
                                LEFT JOIN btype c ON a.btypeid = c.typeid
                      WHERE     @szBeginData <= b.[date]
                                AND @szEndData >= b.[date]
                                AND b.vchtype IN ( 100, 101, 11, 45, 26, 24,
                                                   13, 12, 222, 224, 4, 36, 93,
                                                   115, 66 )
                                AND a.btypeid LIKE @szbtypeid + '%'
                    ) v
                    LEFT JOIN atype aa ON v.atypeid = aa.typeid
                                          AND v.BranchId = aa.BranchId
            WHERE  -- v.BranchID LIKE @Branchid + '%'  AND 
					EXISTS ( SELECT 1
                                 FROM   FN_GetPowerRangeBCList(@OperatorID, @Branchid)
                                 WHERE  BranchID = v.branchid )
            ORDER BY v.vchcode	
            IF @@rowcount = 0 
                GOTO error2
            GOTO succee

        END
    IF ( @szAtypeId = @AR_ID )
        OR ( @szAtypeId = @AP_ID ) 
        BEGIN
            IF @cMode = 'BK' 
                SELECT  @szEtypeId = '%%'
            IF @cMode <> 'QueryConBtype' 
                BEGIN
                    SELECT  v.*,
                            aa.fullname AS afullname
                    FROM    ( SELECT    a.vchcode,
                                        a.vchtype,
                                        a.atypeid,
                                        a.date,
                                        a.branchid,
                                        b.redold,
                                        c.fullname AS bfullname,
                                        b.number,
                                        b.summary AS comment,
                                        a.total,
                                        CASE WHEN a.total > 0 THEN a.total
                                             ELSE 0
                                        END AS increase,
                                        CASE WHEN a.total < 0
                                             THEN -1 * a.total
                                             ELSE 0
                                        END AS reduce,
                                        -( a.Total ) AS ReverseTotal,
                                        a.redword
                              FROM      dlyndx b
                                        INNER JOIN dlya a ON b.vchcode = a.vchcode
                                        LEFT JOIN btype c ON a.btypeid = c.typeid
                              WHERE     @szBeginData <= b.[date]
                                        AND @szEndData >= b.[date]
                                        AND a.atypeid = @AR_ID                                       
                                        AND a.btypeid LIKE @szbtypeid + '%'
                                        AND b.etypeid LIKE @szetypeid + '%'
                              UNION ALL
                              SELECT    a.vchcode,
                                        a.vchtype,
                                        a.atypeid,
                                        a.date,
                                        a.branchid,
                                        b.redold,
                                        c.fullname AS bfullname,
                                        b.number,
                                        b.summary AS comment,
                                        -1 * a.total total,
                                        CASE WHEN a.total < 0
                                             THEN -1 * a.total
                                             ELSE 0
                                        END AS increase,
                                        CASE WHEN a.total > 0 THEN a.total
                                             ELSE 0
                                        END AS reduce,
                                        a.total AS ReverseTotal,
                                        a.redword
                              FROM      dlyndx b
                                        INNER JOIN dlya a ON b.vchcode = a.vchcode
                                        LEFT JOIN btype c ON a.btypeid = c.typeid
                              WHERE     @szBeginData <= b.[date]
                                        AND @szEndData >= b.[date]
                                        AND a.atypeid = @AP_ID
                                        AND a.btypeid LIKE @szbtypeid + '%'
                                        AND b.etypeid LIKE @szetypeid + '%'
                                        UNION ALL  --预收
                              SELECT    a.vchcode,
                                        a.vchtype,
                                        a.atypeid,
                                        a.date,
                                        a.branchid,
                                        b.redold,
                                        c.fullname AS bfullname,
                                        b.number,
                                        b.summary AS comment,
                                        -1 * a.total total,
                                        CASE WHEN a.total < 0
                                             THEN -1 * a.total
                                             ELSE 0
                                        END AS increase,
                                        CASE WHEN a.total > 0 THEN a.total
                                             ELSE 0
                                        END AS reduce,
                                        a.total AS ReverseTotal,
                                        a.redword
                              FROM      dlyndx b
                                        INNER JOIN dlya a ON b.vchcode = a.vchcode
                                        LEFT JOIN btype c ON a.btypeid = c.typeid
                              WHERE     @szBeginData <= b.[date]
                                        AND @szEndData >= b.[date]
                                        AND a.atypeid IN ('0000200888')                                        
                                        AND @IncludeYSYF = '1'
                                        AND @szAtypeId = @AR_ID
                                        AND a.btypeid LIKE @szbtypeid + '%'
                                        AND b.etypeid LIKE @szetypeid + '%'       
                                        UNION ALL  --预付
                              SELECT    a.vchcode,
                                        a.vchtype,
                                        a.atypeid,
                                        a.date,
                                        a.branchid,
                                        b.redold,
                                        c.fullname AS bfullname,
                                        b.number,
                                        b.summary AS comment,
                                        -1 * a.total total,                                        
                                        CASE WHEN a.total > 0 THEN a.total
                                             ELSE 0
                                        END AS increase,
                                             CASE WHEN a.total < 0 --注意此处的写法，程序里面把这两个字段是调整了的，这里也要相应调整一下
                                             THEN -1*a.total
                                             ELSE 0
                                        END AS reduce,
                                        
                                        a.total AS ReverseTotal,
                                        a.redword
                              FROM      dlyndx b
                                        INNER JOIN dlya a ON b.vchcode = a.vchcode
                                        LEFT JOIN btype c ON a.btypeid = c.typeid
                              WHERE     @szBeginData <= b.[date]
                                        AND @szEndData >= b.[date]
                                        AND a.atypeid IN ('0000100888')                                        
                                        AND @IncludeYSYF = '1'
                                        AND @szAtypeId = @AP_ID
                                        AND a.btypeid LIKE @szbtypeid + '%'
                                        AND b.etypeid LIKE @szetypeid + '%'                                    
                                        
                            ) v --select * from dlya where vchcode = 13
                            LEFT JOIN atype aa ON v.atypeid = aa.typeid
                                                  AND v.branchid = aa.branchid
                    WHERE   --v.branchid LIKE @Branchid + '%' AND
                             EXISTS ( SELECT 1
                                         FROM   FN_GetPowerRangeBCList(@OperatorID, @Branchid)
                                         WHERE  BranchID = v.branchid )
                    ORDER BY v.vchcode
                END
            ELSE 
                BEGIN
                    SELECT  v.*,
                            atypeid
                    FROM    ( SELECT    a.vchcode,
                                        a.vchtype,
                                        a.atypeid,
                                        a.date,
                                        b.redold,
                                        a.btypeid,
                                        b.number,
                                        b.summary AS comment,
                                        a.total,
                                        CASE WHEN a.total > 0 THEN a.total
                                             ELSE 0
                                        END AS increase,
                                        CASE WHEN a.total < 0
                                             THEN -1 * a.total
                                             ELSE 0
                                        END AS reduce,
                                        -( a.Total ) AS ReverseTotal,
                                        a.redword,
                                        b.BranchId
                              FROM      dlyndx b
                                        INNER JOIN dlya a ON b.vchcode = a.vchcode
                                        LEFT JOIN btype c ON a.btypeid = c.typeid
                              WHERE     @szBeginData <= b.[date]
                                        AND @szEndData >= b.[date]
                                        AND a.atypeid = @AR_ID
                                        AND b.vchtype IN ( 34, 6, 28, 11, 45,
                                                           12, 13, 100, 101,
                                                           222, 224, 24, 66, 4,
                                                           26 )
                                        AND a.btypeid LIKE @szbtypeid + '%'
                                        AND b.etypeid LIKE @szetypeid + '%'
                              UNION ALL
                              SELECT    a.vchcode,
                                        a.vchtype,
                                        a.atypeid,
                                        a.date,
                                        b.redold,
                                        a.btypeid,
                                        b.number,
                                        b.summary AS comment,
                                        -1 * a.total total,
                                        CASE WHEN a.total < 0
                                             THEN -1 * a.total
                                             ELSE 0
                                        END AS increase,
                                        CASE WHEN a.total > 0 THEN a.total
                                             ELSE 0
                                        END AS reduce,
                                        a.total AS ReverseTotal,
                                        a.redword,
                                        b.BranchId
                              FROM      dlyndx b
                                        INNER JOIN dlya a ON b.vchcode = a.vchcode
                                        LEFT JOIN btype c ON a.btypeid = c.typeid
                              WHERE     @szBeginData <= b.[date]
                                        AND @szEndData >= b.[date]
                                        AND a.atypeid = @AP_ID
                                        AND b.vchtype IN ( 34, 6, 28, 11, 45,
                                                           12, 13, 100, 101,
                                                           222, 224, 24, 66, 4,
                                                           26 )
                                        AND a.btypeid LIKE @szbtypeid + '%'
                                        AND b.etypeid LIKE @szetypeid + '%'
                              UNION ALL
                              SELECT DISTINCT
                                        a.vchcode,
                                        a.vchtype,
                                        '' AS atypeid,
                                        a.date,
                                        b.redold,
                                        a.btypeid,
                                        b.number,
                                        b.summary AS comment,
                                        0 AS total,
                                        0 AS increase,
                                        0 AS reduce,
                                        0 AS ReverseTotal,
                                        a.redword,
                                        b.BranchId
                              FROM      dlyndx b
                                        INNER JOIN ( SELECT DISTINCT
                                                            btypeid,
                                                            vchcode,
                                                            vchtype,
                                                            [date],
                                                            redword
                                                     FROM   dlya
                                                     WHERE  vchcode NOT IN (
                                                            SELECT  vchcode
                                                            FROM    dlya
                                                            WHERE   atypeid = '0000100005'
                                                                    OR atypeid = '0000200001' )
                                                   ) a ON b.vchcode = a.vchcode
                                        LEFT JOIN btype c ON a.btypeid = c.typeid
                              WHERE     @szBeginData <= b.[date]
                                        AND @szEndData >= b.[date]
                                        AND b.vchtype IN ( 34, 6, 28, 11, 45,
                                                           12, 13, 100, 101,
                                                           222, 224, 24, 66, 4,
                                                           26 )
                                        AND a.btypeid LIKE @szbtypeid + '%'
                                        AND b.etypeid LIKE @szetypeid + '%'
                            ) v
                            LEFT JOIN atype aa ON v.atypeid = aa.typeid
                                                  AND v.branchid = aa.branchid
                    WHERE   --v.BranchID LIKE @Branchid + '%' AND 
                            EXISTS ( SELECT 1
                                         FROM   FN_GetPowerRangeBCList(@OperatorID, @Branchid)
                                         WHERE  BranchID = v.branchid )
                END
        END
	--	得到往来单位的回款明细
	--	回款统计应为科目为现金、银行，单据为收款单，销售单，销售退货单三种单据
    ELSE 
        BEGIN
            IF @nESonnum > 0
                AND @szEtypeid <> '00000' 
                BEGIN
                    PRINT @szEtypeId
                    SELECT  da.[vchcode],
                            da.[vchtype],
                            da.[atypeid],
                            ISNULL(da.[total], 0) AS Total,
                            da.[date],
                            ISNULL(dn.[number], '') AS [number],
                            ISNULL(dn.[summary], '') AS comment,
                            da.etypeid,
                            da.atypeid,
                            v.typeid AS vtypeid,
                            dn.redold,
                            CASE WHEN da.total > 0 THEN ISNULL(da.total, 0)
                                 ELSE 0
                            END AS Increase,
                            CASE WHEN da.total < 0 THEN ISNULL(da.total, 0)
                                 ELSE 0
                            END AS Reduce,
                            -( da.Total ) AS ReverseTotal,
                            da.redword
                    FROM    ( SELECT    *
                              FROM      DlyA
                              WHERE     @szBeginData <= [Date]
                                        AND @szEndData >= [Date]
                                        AND ( ( LEFT([atypeid], LEN(@CASH_ID)) = @CASH_ID )
                                              OR ( LEFT([atypeid],
                                                        LEN(@CASH_BANK_ID)) = @CASH_BANK_ID )
                                            )
                                        AND [btypeid] LIKE @szBtypeId
                                        AND LEFT([etypeId], LEN(@szEtypeId)) LIKE @szEtypeId
                            ) da LEFT JOIN employee e on da.[etypeId]=e.[typeid],
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND [vchtype] IN ( @SALEBILL,
                                                           @SALEBACKBILL,
                                                           @GETMONEYBILL, 250,
                                                           222, 13, 12, 24,
                                                           100, 101, 26, 224 )
                            ) dn ,
                            atype a,
                            vchtype v
                    WHERE   da.[atypeid] = a.[typeid]
                            AND da.[vchcode] = dn.[vchcode]
                            AND da.[vchtype] = v.[vchtype]
                    ORDER BY da.[vchcode]
                END
            ELSE 
                BEGIN
			
                    SELECT  da.[vchcode],
                            da.[vchtype],
                            da.[atypeid],
                            ISNULL(da.[total], 0) AS Total,
                            da.[date],
                            ISNULL(dn.[number], '') AS [number],
                            ISNULL(dn.[summary], '') AS comment,
                            da.etypeid,
                            da.atypeid,
                            v.typeid AS vtypeid,
                            dn.redold,
                            CASE WHEN da.total > 0 THEN ISNULL(da.total, 0)
                                 ELSE 0
                            END AS Increase,
                            CASE WHEN da.total < 0 THEN ISNULL(da.total, 0)
                                 ELSE 0
                            END AS Reduce,
                            -( da.Total ) AS ReverseTotal,
                            da.redword
                    FROM    ( SELECT    *
                              FROM      DlyA
                              WHERE     @szBeginData <= [Date]
                                        AND @szEndData >= [Date]
                                        AND ( ( LEFT([atypeid], LEN(@CASH_ID)) = @CASH_ID )
                                              OR ( LEFT([atypeid],
                                                        LEN(@CASH_BANK_ID)) = @CASH_BANK_ID )
                                            )
                                        AND [btypeid] LIKE @szBtypeId
                                        AND [etypeId] LIKE @szEtypeId
                            ) da LEFT JOIN employee e on da.[etypeId]=e.[typeid] ,
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND [vchtype] IN ( @SALEBILL,
                                                           @SALEBACKBILL,
                                                           @GETMONEYBILL, 250,
                                                           222, 13, 12, 24,
                                                           100, 101, 26, 224 )
                            ) dn,
                            atype a,
                            vchtype v
                    WHERE   da.[atypeid] = a.[typeid]
                            AND da.[vchcode] = dn.[vchcode]
                            AND da.[vchtype] = v.[vchtype]
                    ORDER BY da.[vchcode]
                END
        END
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--	得到库存商品的明细
    GetPtype:
    IF @szKtypeID = '%%' 
        SET @szKtypeID = ''
    IF @szBTypeId = '%%' 
        SET @szBTypeId = ''
    IF OBJECT_ID('tempdb..#detail1') IS NOT NULL 
        DROP TABLE #detail1
    SELECT  vchcode,
            vchtype,
            SUM(Qty) AS Qty,
            SUM(Total) AS Total,
            date,
            number,
            comment,
            ptypeid,
            RedOld,
            redword,
            KtypeId,
            PSONKSON.UnitRate
    INTO    #detail1
    FROM    ( SELECT    a.[vchcode],
                        a.[vchtype],
                        ISNULL(a.[qty], 0) AS Qty,
                        ISNULL(a.[costtotal], 0) AS Total,
                        a.[date],
                        --dlyorder,
                        ISNULL(b.[number], '') AS [number],
                        ISNULL(b.[summary], '') AS comment,
                        ptypeid,
                        b.RedOld,
                        a.redword,
                        a.KtypeId,
                        C.UnitRate1 AS UnitRate
              --FROM      ( SELECT    *
              --            FROM      Dlydata
              --            WHERE     @szBeginData <= [date]
              --                      AND @szEndData >= [date]
              --                      AND [pdetail] <> 2
              --          ) a,
              --          ( SELECT    *
              --            FROM      DlyNdx
              --            WHERE     @szBeginData <= [date]
              --                      AND @szEndData >= [date]
              --          ) b,
              FROM      dbo.DlyNdx b,
                        dbo.DlyData a,
                        FN_GetPowerRangePList(@OperatorId, '') c
              WHERE     a.[ptypeId] LIKE @szPtypeId + '%'
                        AND EXISTS ( SELECT 1
                                     FROM   FN_GetStockListOfBranch(@OperatorID, @szBTypeId, @szKtypeID) bb
                                     WHERE  a.KtypeId = bb.KtypeId )
                        AND a.[vchcode] = b.[vchcode]
                        AND a.[ptypeid] = c.[typeid]
                        AND a.PDetail <> 2
                        AND CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND a.Qty<0)))) THEN CONVERT(varchar(12) ,b.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,b.AccountTime, 23 ) ELSE a.[date] END BETWEEN @szBeginData AND @szEndData
                        AND c.Stop IN ( CASE @IsStop
                                          WHEN 0 THEN c.stop
                                          ELSE 0
                                        END )--是否包含停用商品
              
            ) AS PSONKSON
    GROUP BY vchcode,
            vchtype,
            date,
            number,
            comment,
            ptypeid,
            RedOld,
            redword,
            KtypeId,
            --dlyorder,
            PSONKSON.UnitRate
    ORDER BY [vchcode]
	
    SELECT  vchcode,
            vchtype,
            qty,
            CASE WHEN Qty < 0 THEN ABS(qty)
                 ELSE 0
            END qtyout,
            CASE WHEN qty >= 0 THEN qty
                 ELSE 0
            END qtyin,
            Total,
            date,
            number,
            comment,
            ptypeid,
            RedOld,
            redword,
            unitrate
    FROM    #detail1
    ORDER BY [vchcode],
            [date],
            redold
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--	得到自营店库存商品的明细
    GetSelf:
    IF OBJECT_ID('tempdb..#detail1s') IS NOT NULL 
        DROP TABLE #detail1s
    SELECT  vchcode,
            vchtype,
            Qty,
            Total,
            date,
            number,
            comment,
            PtypeId,
            Pusercode,
            RedOld,
            redword
    INTO    #detail1s
    FROM    ( SELECT    a.[vchcode],
                        a.[vchtype],
                        ISNULL(a.[qty], 0) AS Qty,
                        ISNULL(a.[costtotal], 0) AS Total,
                        a.[date],
                        ISNULL(b.[number], '') AS [number],
                        ISNULL(b.[summary], '') AS comment,
                        c.[TypeId] AS PtypeId,
                        c.usercode AS Pusercode,
                        b.RedOld,
                        a.redword
              FROM      ( SELECT    *
                          FROM      dlydata
                          WHERE     @szBeginData <= [date]
                                    AND @szEndData >= [date]
                                    AND [pdetail] <> 2
                        ) a,
                        ( SELECT    *
                          FROM      DlyNdx
                          WHERE     @szBeginData <= [date]
                                    AND @szEndData >= [date]
                        ) b,
                        FN_GetPowerRangePList(@OperatorId, '') c
              WHERE     LEFT(a.[ptypeId], LEN(@szPtypeId)) LIKE @szPtypeId
                        AND LEFT(a.[ktypeId], LEN(@szKtypeId)) LIKE @szKtypeId
                        AND LEFT(a.ktypeid, 5) = '00007'
                        AND a.[vchcode] = b.[vchcode]
                        AND a.[ptypeid] = c.[typeid]
              UNION ALL
              SELECT    a.[vchcode],
                        a.[vchtype],
                        ISNULL(a.[qty], 0) AS Qty,
                        ISNULL(a.[costtotal], 0) AS Total,
                        a.[date],
                        ISNULL(b.[number], '') AS [number],
                        ISNULL(b.[summary], '') AS comment,
                        c.[TypeId] AS PtypeId,
                        c.usercode AS Pusercode,
                        b.RedOld,
                        a.redword
              FROM      ( SELECT    *
                          FROM      dlydata
                          WHERE     billtype = 3
                                    AND @szBeginData <= [date]
                                    AND @szEndData >= [date]
                                    AND ( [ktypeid] <> @BORROW_KTYPE
                                          AND [ktypeid] <> @LEND_KTYPE
                                          AND vchtype NOT IN ( '73', '89' )
                                          AND [pdetail] <> 2
                                        )
                        ) a,
                        ( SELECT    *
                          FROM      DlyNdx
                          WHERE     @szBeginData <= [date]
                                    AND @szEndData >= [date]
                        ) b,
                        FN_GetPowerRangePList(@OperatorId, '') c
              WHERE     a.[atypeId] = @GOOD_ID
                        AND LEFT(a.[ptypeId], LEN(@szPtypeId)) LIKE @szPtypeId
                        AND LEFT(a.[ktypeId], LEN(@szKtypeId)) LIKE @szKtypeId
                        AND LEFT(a.ktypeid, 5) = '00007'
                        AND a.[vchcode] = b.[vchcode]
                        AND a.[ptypeid] = c.[typeid]
            ) AS PSONKSON
    ORDER BY [vchcode]
	
    SELECT  vchcode,
            vchtype,
            qty,
            CASE WHEN Qty < 0 THEN ABS(qty)
                 ELSE 0
            END qtyout,
            CASE WHEN qty >= 0 THEN qty
                 ELSE 0
            END qtyin,
            Total,
            date,
            number,
            comment,
            PtypeId,
            Pusercode,
            RedOld,
            redword
    FROM    #detail1s
    ORDER BY vchcode
	
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--   得到库存状况表的单据明细
    GetStockBillDetail:
    BEGIN
        IF @szKtypeId = '%%' 
            SET @szKtypeId = ''
        IF @szBtypeId = '%%' 
            SET @szBtypeId = ''
        IF OBJECT_ID('tempdb..#detail1kczk') IS NOT NULL 
            DROP TABLE #detail1kczk
        SELECT  vchcode,
                vchtype,
                Qty,
                Total,
                date,
                number,
                comment,
                PtypeId,
                Pusercode,
                RedOld,
                redword,
                dlyorder
        INTO    #detail1kczk
        FROM    ( SELECT    b.[vchcode],
                            b.[vchtype],
                            ISNULL(a.[qty], 0) AS Qty,
                            ISNULL(( a.[costtotal] ), 0) AS Total,
                            a.[date],
                            dlyorder,
                            ISNULL(b.[number], '') AS [number],
                            ISNULL(b.[summary], '') AS comment,
                            c.[typeId] AS PtypeId,
                            c.usercode AS Pusercode,
                            b.RedOld,
                            a.redword
                  FROM      ( SELECT    ptypeid,
                                        ktypeid,
                                        date,
                                        vchcode,
                                        vchtype,
                                        Qty,
                                        costtotal,
                                        redword,
                                        dlyorder
                              FROM      Dlydata
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND [PDETAIL] <> 2
                                        AND LEFT([ptypeId], LEN(@szPtypeId)) LIKE @szPtypeId
                                        + '%'
                                        AND EXISTS ( SELECT 1
                                                     FROM   FN_GetStockListOfBranch(@OperatorID, @szBTypeId, @szKtypeID) bb
                                                     WHERE  Dlydata.KtypeId = bb.KtypeId )
                            ) a,
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                            ) b,
                            FN_GetPowerRangePList(@OperatorId, '') c
                  WHERE     a.[ptypeId] LIKE @szPtypeId + '%'
                            AND a.[vchcode] = b.[vchcode]
                            AND a.[ptypeid] = c.[typeid]
                ) AS PSONKSON
        ORDER BY [vchcode]
	
	
        SELECT  [vchcode],
                [vchtype],
                SUM(qty),
                CASE WHEN SUM(qty) < 0 THEN SUM(ABS(qty))
                     ELSE 0
                END AS qtyout,
                CASE WHEN SUM(qty) >= 0 THEN SUM(qty)
                     ELSE 0
                END AS qtyin,
                SUM(Total),
                [date],
                [number],
                comment,
                PtypeId,
                Pusercode,
                RedOld,
                Redword
        FROM    #detail1kczk
        GROUP BY PtypeId,
                Pusercode,
                RedOld,
                Redword,
                [vchcode],
                [vchtype],
                [date],
                [number],
                comment,
                dlyorder
        ORDER BY vchcode
    END
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee

--加盟店库存明细单据单据具体类别：1 进货类，2销售类，3库存类，4加盟店销售类，5加盟店库存类,6财务类，7其他类
    GetStockJOINBillDetail:
    IF @szKtypeId = '%%' 
        SET @szKtypeId = ''
    IF @szBtypeId = '%%' 
        SET @szBtypeId = ''
    IF OBJECT_ID('tempdb..#detail1kczkJoin') IS NOT NULL 
        DROP TABLE #detail1kczkJoin
    SELECT  vchcode,
            vchtype,
            Qty,
            Total,
            date,
            number,
            comment,
            ptypeid,
            RedOld,
            redword
    INTO    #detail1kczkJoin
    FROM    ( SELECT    b.[vchcode],
                        b.[vchtype],
                        ISNULL(a.[qty], 0) AS Qty,
                        ISNULL(( a.[costtotal] ), 0) AS Total,
                        a.[date],
                        ISNULL(b.[number], '') AS [number],
                        ISNULL(b.[summary], '') AS comment,
                        ptypeid,
                        b.RedOld,
                        a.redword
              FROM      ( SELECT    ptypeid,
                                    ktypeid,
                                    date,
                                    vchcode,
                                    vchtype,
                                    Qty,
                                    costtotal,
                                    redword
                          FROM      Dlydata xx
                          WHERE     EXISTS ( SELECT 1
                                             FROM   FN_GetStockListOfBranch(@OperatorID, @szBTypeId, @szKtypeID) bb
                                             WHERE  xx.KtypeId = bb.KtypeId )
                                    AND ( billtype IN ( 4, 5 )
                                          OR ( billtype = 2
                                               AND vchtype IN ( 222, 224 )
                                               AND usedtype = CASE WHEN vchtype IN ( 222, 224 ) THEN ''
                                                                   ELSE usedtype
                                                              END
                                             )
                                        )
                                    AND @szBeginData <= [date]
                                    AND @szEndData >= [date]
                                    AND [PDETAIL] <> 2
                                    AND ptypeId LIKE @szPtypeId + '%'
		--and  ktypeId like @szKtypeId+'%'
                          
                        ) a,
                        ( SELECT    *
                          FROM      DlyNdx
                          WHERE     ( billtype IN ( 4, 5 )
                                      OR ( billtype = 2
                                           AND vchtype IN ( 222, 224 )
                                         )
                                    )
                                    AND @szBeginData <= [date]
                                    AND @szEndData >= [date]
                        ) b,
                        FN_GetPowerRangePList(@OperatorId, '') c
              WHERE     a.[ptypeId] LIKE @szPtypeId + '%'
                        AND a.[vchcode] = b.[vchcode]
                        AND a.[ptypeid] = c.[typeid]
            ) AS PSONKSON
    ORDER BY [vchcode]
	
	
    SELECT  [vchcode],
            [vchtype],
            qty,
            CASE WHEN qty < 0 THEN ABS(qty)
                 ELSE 0
            END AS qtyout,
            CASE WHEN qty >= 0 THEN qty
                 ELSE 0
            END AS qtyin,
            Total,
            [date],
            [number],
            comment,
            ptypeid,
            RedOld,
            redword
    FROM    #detail1kczkJoin
    ORDER BY vchcode
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee

---------得到加盟店的库存明细
    GetJoinStock:
    BEGIN
        IF @szBTypeId = '%'
            OR @szBTypeId = '%%' 
            SET @szBTypeId = ''
        IF @szKTypeId = '%'
            OR @szKTypeId = '%%' 
            SET @szKTypeId = ''
        IF ( LEN(@szBTypeId) >= 5 )
            AND ( @szKTypeId = '00004' )  --如果选择了加盟店机构则取消默认的仓库类
            SET @szKTypeId = ''
        IF OBJECT_ID('tempdb..#detail11') IS NOT NULL 
            DROP TABLE #detail11
        SELECT  vchcode,
                vchtype,
                Qty,
                Total,
                date,
                number,
                comment,
                ptypeid,
                RedOld,
                redword
        INTO    #detail11
        FROM    ( SELECT    a.[vchcode],
                            a.[vchtype],
                            ISNULL(a.[qty], 0) AS Qty,
                            ISNULL(( a.[costtotal] ), 0) AS Total,
                            a.[date],
                            ISNULL(b.[number], '') AS [number],
                            ISNULL(b.[summary], '') AS comment,
                            ptypeid,
                            b.RedOld,
                            a.redword
                  FROM      ( SELECT    *
                              FROM      dlydata
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND vchtype IN ( 226, 227 )
                            ) a,
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND vchtype IN ( 226, 227 )
                            ) b,
                            FN_GetPowerRangePList(@OperatorId, '') c
                  WHERE     LEFT(a.[ptypeId], LEN(@szPtypeId)) LIKE @szPtypeId
                            + '%'
                            AND EXISTS ( SELECT 1
                                         FROM   FN_GetStockListOfBranch(@OperatorID, @szBTypeId, @szKtypeID) bb
                                         WHERE  a.KtypeId = bb.KtypeId )
                            AND a.[vchcode] = b.[vchcode]
                            AND a.[ptypeid] = c.[typeid]
                  UNION ALL
                  SELECT    a.[vchcode],
                            a.[vchtype],
                            ISNULL(a.qty, 0) AS Qty,
                            ( CASE a.vchtype
                                WHEN 26 THEN ISNULL(( a.bargainTotal ), 0)
                                ELSE ISNULL(( a.costTotal ), 0)
                              END ) AS Total,
                            a.[date],
                            ISNULL(b.[number], '') AS [number],
                            ISNULL(b.[summary], '') AS comment,
                            ptypeid,
                            b.RedOld,
                            a.redword
                  FROM      ( SELECT    *
                              FROM      dlydata
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND ( vchtype IN ( 222, 224 )
                                              AND usedtype = CASE WHEN vchtype IN ( 222, 224 ) THEN ''
                                                                  ELSE '1'
                                                             END
                                            )
                            ) a,
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND ( vchtype IN ( 224, 222 ) )
                            ) b,
                            FN_GetPowerRangePList(@OperatorId, '') c
                  WHERE     LEFT(a.[ptypeId], LEN(@szPtypeId)) LIKE @szPtypeId
                            + '%'
                            AND EXISTS ( SELECT 1
                                         FROM   FN_GetStockListOfBranch(@OperatorID, @szBTypeId, @szKtypeID) bb
                                         WHERE  a.KtypeId = bb.KtypeId )
                            AND a.[vchcode] = b.[vchcode]
                            AND a.[ptypeid] = c.[typeid]
                  UNION ALL
                  SELECT    a.[vchcode],
                            a.[vchtype],
                            ISNULL(a.qty, 0) AS Qty,
                            ISNULL(( a.[costtotal] ), 0) AS Total,
                            a.[date],
                            ISNULL(b.[number], '') AS [number],
                            ISNULL(b.[summary], '') AS comment,
                            ptypeid,
                            b.RedOld,
                            a.redword
                  FROM      ( SELECT    *
                              FROM      dlydata
                              WHERE     usedtype = '1'
                                        AND @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND vchtype IN ( 140, 141, 142, 143,
                                                         144 )
                            ) a,
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND vchtype IN ( 140, 141, 142, 143,
                                                         144 )
                            ) b,
                            FN_GetPowerRangePList(@OperatorId, '') c
                  WHERE     LEFT(a.[ptypeId], LEN(@szPtypeId)) LIKE @szPtypeId
                            + '%'
                            AND EXISTS ( SELECT 1
                                         FROM   FN_GetStockListOfBranch(@OperatorID, @szBTypeId, @szKtypeID) bb
                                         WHERE  a.KtypeId = bb.KtypeId )
                            AND a.[vchcode] = b.[vchcode]
                            AND a.[ptypeid] = c.[typeid]
                ) AS PSONKSON
        ORDER BY [vchcode]
		
        SELECT  vchcode,
                [vchtype],
                qty,
                CASE WHEN qty < 0 THEN ABS(qty)
                     ELSE 0
                END AS qtyout,
                CASE WHEN qty >= 0 THEN qty
                     ELSE 0
                END AS qtyin,
                Total,
                [date],
                [number],
                comment,
                PtypeId,
                RedOld,
                redword
        FROM    #detail11
        ORDER BY vchcode
    END
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--	得到职员的明细
    GetEtype:
--	得到一个单位，一个职员的应收应付款
    IF ( @szAtypeId = @AR_ID )
        OR ( @szAtypeId = @AP_ID ) 
        BEGIN

            SELECT  da.[vchcode],
                    da.[vchtype],
                    ISNULL(da.[total], 0) AS Total,
                    da.[date],
                    da.[atypeid],
                    ISNULL(dn.[number], '') AS [number],
                    ISNULL(dn.[summary], '') AS comment,
                    dn.redold,
                    da.redword
            FROM    ( SELECT    *
                      FROM      DlyA
                      WHERE     @szBeginData <= [Date]
                                AND @szEndData >= [Date]
                                AND ( [atypeId] = @AR_ID
                                      OR [atypeId] = @AP_ID
                                    )
                                AND [etypeid] LIKE @szEtypeId
                                AND [btypeId] LIKE @szBtypeId
                    ) da,
                    ( SELECT    *
                      FROM      DlyNdx
                      WHERE     @szBeginData <= [date]
                                AND @szEndData >= [date]
                    ) dn
            WHERE   da.[vchcode] = dn.[vchcode]
            ORDER BY da.[vchcode]
        END
--	得到职员的回款明细
--	回款统计应为科目为现金、银行，单据为收款单，销售单，销售退货单三种单据
    ELSE 
        BEGIN
            IF @nBSonnum > 0 
                BEGIN

                    SELECT  da.[vchcode],
                            da.[vchtype],
                            da.[atypeid],
                            ISNULL(da.[total], 0) AS Total,
                            da.[date],
                            ISNULL(dn.[number], '') AS [number],
                            ISNULL(dn.[summary], '') AS comment,
                            ISNULL(b.[fullname], '') AS Bfullname,
                            a.[fullname] AS Afullname,
                            v.[fullname] AS Vfullname,
                            dn.redold,
                            da.RedWord
                    FROM    ( SELECT    *
                              FROM      DlyA
                              WHERE     @szBeginData <= [Date]
                                        AND @szEndData >= [Date]
                                        AND ( ( LEFT([atypeid], LEN(@CASH_ID)) = @CASH_ID )
                                              OR ( LEFT([atypeid],
                                                        LEN(@CASH_BANK_ID)) = @CASH_BANK_ID )
                                            )
                                        AND [etypeid] LIKE @szEtypeId
                                        AND LEFT([btypeId], LEN(@szBtypeId)) LIKE @szBtypeId
                            ) da,
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND [vchtype] IN ( @SALEBILL,
                                                           @SALEBACKBILL,
                                                           @GETMONEYBILL, 222,
                                                           224, 250, 12, 13,
                                                           24, 26 )
                            ) dn,
                            btype b,
                            atype a,
                            vchtype v
                    WHERE   da.[btypeId] = b.[typeid]
                            AND da.[atypeid] = a.[typeid]
                            AND da.[vchcode] = dn.[vchcode]
                            AND da.[vchtype] = v.[vchtype]
                    ORDER BY da.[vchcode]
                END
            ELSE 
                BEGIN
                    SELECT  da.[vchcode],
                            da.[vchtype],
                            da.[atypeid],
                            ISNULL(da.[total], 0) AS Total,
                            da.[date],
                            ISNULL(dn.[number], '') AS [number],
                            ISNULL(dn.[summary], '') AS comment,
                            ISNULL(b.[fullname], '') AS Bfullname,
                            a.[fullname] AS Afullname,
                            v.[fullname] AS Vfullname,
                            dn.redold,
                            da.redword
                    FROM    ( SELECT    *
                              FROM      DlyA
                              WHERE     @szBeginData <= [Date]
                                        AND @szEndData >= [Date]
                                        AND ( ( LEFT([atypeid], LEN(@CASH_ID)) = @CASH_ID )
                                              OR ( LEFT([atypeid],
                                                        LEN(@CASH_BANK_ID)) = @CASH_BANK_ID )
                                            )
                                        AND [etypeid] LIKE @szEtypeId
                                        AND [btypeId] LIKE @szBtypeId
                            ) da,
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND [vchtype] IN ( @SALEBILL,
                                                           @SALEBACKBILL,
                                                           @GETMONEYBILL, 222,
                                                           224, 250, 12, 13,
                                                           24, 26 )
                            ) dn,
                            btype b,
                            atype a,
                            vchtype v
                    WHERE   da.[btypeId] = b.[typeid]
                            AND da.[atypeid] = a.[typeid]
                            AND da.[vchcode] = dn.[vchcode]
                            AND da.[vchtype] = v.[vchtype]
                    ORDER BY da.[vchcode]
                END
        END
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--	得到进货的明细(包括受托结算)
    GetBuy:

    SELECT  a.[vchcode],
            a.[vchtype],
            ISNULL(a.[qty], 0) AS Qty,
            ISNULL(a.[tax_total], 0) AS Total,
            a.[date],
            ISNULL(b.[number], '') AS [number],
            ISNULL(b.[summary], '') AS comment,
            a.redold,
            a.ptypeid,
            a.btypeid,
            a.ktypeid,
            a.redword
    FROM    Dlydata a,
            dlyndx b
    WHERE   @szBeginData <= a.[date]
            AND @szEndData >= a.[date]
            AND a.vchcode = b.vchcode
            AND a.billtype = 1
            AND a.ptypeid LIKE @szptypeId + '%'
            --AND a.ktypeid LIKE @szKtypeId + '%'
            AND a.btypeid LIKE @szbtypeId + '%'
           -- AND a.BranchId LIKE @Branchid + '%'
           
           AND EXISTS ( SELECT 1 FROM   FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) FilterK WHERE  a.ktypeId = Filterk.KtypeId )
           
            AND EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangePList(@OperatorId, '') FilterP
                         WHERE  a.PtypeId = FilterP.TypeId )    --商品权限         	     
            AND EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangeEList(@OperatorId, '') FilterE
                         WHERE  a.EtypeId = FilterE.TypeId )    --经手人权限
            AND EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangeBCList(@OperatorId, '') FilterBC
                         WHERE  a.branchid = FilterBC.branchid ) --机构权限      										     
    ORDER BY a.[vchcode]
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--	得到进货的明细(不包括受托结算)
    GetBuy1:
    SELECT  a.[vchcode],
            a.[vchtype],
            ISNULL(a.[qty], 0) AS Qty,
            ISNULL(a.[tax_total], 0) AS Total,
            a.[date],
            ISNULL(b.[number], '') AS [number],
            ISNULL(b.[summary], '') AS comment,
            a.ptypeid,
            a.btypeid,
            a.ktypeid,
            b.redold,
            a.redword
    FROM    Dlydata a,
            dlyndx b
    WHERE   @szBeginData <= a.[date]
            AND @szEndData >= a.[date]
            AND a.btypeid LIKE @szbtypeId + '%'
            AND a.billtype = 1
            AND a.[ptypeId] LIKE @szPtypeId + '%'
            AND a.[vchcode] = b.[vchcode]
    ORDER BY a.[vchcode] 
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee

--	得到进货退货的明细
    GetBuyBack:

    SELECT  a.[vchcode],
            a.[vchtype],
            ABS(ISNULL(a.[qty], 0)) AS Qty, 
        --在存储过程中计算增加额和减少额
            ABS(CASE WHEN ISNULL(a.[qty], 0) > 0 THEN ISNULL(a.[qty], 0)
                     ELSE 0
                END) AS InStock,
            ABS(CASE WHEN ISNULL(a.[qty], 0) < 0 THEN ISNULL(a.[qty], 0)
                     ELSE 0
                END) AS OutStock,
            ABS(ISNULL(a.[tax_total], 0)) AS Total,
            a.[date],
            ISNULL(b.[number], '') AS [number],
            ISNULL(b.[summary], '') AS comment,
            a.btypeid,
            a.ktypeid,
            a.ptypeid,
            b.redold,
            a.RedWord
    FROM    Dlydata a,
            dlyndx b
    WHERE   @szBeginData <= a.[date]
            AND @szEndData >= a.[date]
            AND a.[ktypeid] LIKE @szKtypeId + '%'
            AND a.btypeid LIKE @szbtypeId + '%'
            AND a.billtype = 1
            AND a.[ptypeId] LIKE @szPtypeId + '%'
            AND a.[vchcode] = b.[vchcode]
            AND a.vchtype = 6
            AND a.btypeid LIKE @szbtypeid + '%'
    ORDER BY a.[vchcode]

    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--	得到进货退货分析的明细（暂时无用）
    GetBuyandback:

    SELECT  a.[vchcode],
            a.[vchtype],
            ABS(ISNULL(a.[qty], 0)) AS Qty,
            ABS(ISNULL(a.[tax_total], 0)) AS Total,
            a.[date],
            ISNULL(b.[number], '') AS [number],
            ISNULL(b.[summary], '') AS comment,
            a.ptypeid,
            a.btypeid,
            a.ktypeid,
            b.redold,
            a.RedWord
    FROM    Dlydata a,
            DlyNdx b
    WHERE   @szBeginData <= a.[date]
            AND @szEndData >= a.[date]
            AND a.billtype = 1
            AND a.[ktypeid] LIKE @szKtypeId + '%'
            AND a.btypeid LIKE @szbtypeId + '%'
            AND a.[ptypeId] LIKE @szPtypeId + '%'
            AND a.[vchcode] = b.[vchcode]
    ORDER BY a.[vchcode]
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--           得到销售换货的明细
    GetSaleExchange: 
	          
    SELECT  a.[vchcode],
            a.[vchtype],
            ABS(ISNULL(a.[qty], 0)) AS Qty,
            ABS(ISNULL(a.[tax_total], 0)) AS Total,
            a.[date],
            ISNULL(b.[number], '') AS [number],
            ISNULL(b.[summary], '') AS comment,
            a.ptypeid,
            a.btypeid,
            a.ktypeid,
            b.redold,
            a.RedWord--,b.BarterRate,
    FROM    Dlydata a,
            DlyNdx b
    WHERE   a.[ptypeId] LIKE @szPtypeId + '%'
            AND @szBeginData <= a.[date]
            AND @szEndData >= a.[date]
            AND a.[vchcode] = b.[vchcode]
            AND a.Btypeid LIKE @szBtypeId + '%'
            AND a.vchtype = 24
            AND b.BarterType = 0
            AND a.usedtype = 1
    UNION ALL
    SELECT  a.[vchcode],
            a.[vchtype],
            ABS(ISNULL(a.[qty], 0)) AS Qty,
            ABS(ISNULL(a.[tax_total], 0)) AS Total,
            a.[date],
            ISNULL(b.[number], '') AS [number],
            ISNULL(b.[summary], '') AS comment,
            a.ptypeid,
            a.btypeid,
            a.ktypeid,
            b.redold,
            a.RedWord--,b.BarterRate
    FROM    Dlydata a,
            DlyNdx b
    WHERE   a.[ptypeId] LIKE @szPtypeId + '%'
            AND @szBeginData <= a.[date]
            AND @szEndData >= a.[date]
            AND a.[vchcode] = b.[vchcode]
            AND usedtype = CASE WHEN a.vchtype IN ( 222, 224 ) THEN 1
                                ELSE usedtype
                           END
            AND a.Btypeid LIKE @szBtypeId + '%'
            AND a.vchtype IN ( 45, 13, 224 )
            AND b.BarterType = 0
    ORDER BY a.vchcode
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--         得到加盟店零售明细s
    GetJoinSale:      
    IF @szKtypeID = '%%' 
        SET @szKtypeID = ''
    IF @szBtypeID = '%%' 
        SET @szBtypeID = ''
    SELECT  a.[vchcode],
            a.[vchtype],
            ABS(( CASE WHEN ISNULL(a.[qty], 0) > 0 THEN ISNULL(a.[qty], 0)
                       ELSE 0
                  END )) AS InStock,
            ABS(( CASE WHEN ISNULL(a.[qty], 0) < 0 THEN ISNULL(a.[qty], 0)
                       ELSE 0
                  END )) AS OutStock,
            ABS(ISNULL(a.[tax_total], 0)) AS Total,
            a.[date],
            ISNULL(b.[number], '') AS [number],
            ISNULL(b.[summary], '') AS comment,
            a.ptypeid,
            a.btypeid,
            a.ktypeid,
            b.redold,
            a.RedWord
    FROM    DlyData a,
            DlyNdx b
    WHERE   LEFT(a.[ptypeId], LEN(@szPtypeId)) = @szPtypeId
            AND a.vchtype IN ( 226, 227 )
            AND @szBeginData <= a.[date]
            AND @szEndData >= a.[date]
            AND a.[vchcode] = b.[vchcode]
            AND EXISTS ( SELECT 1
                         FROM   FN_GetStockListOfBranch(@OperatorID,
                                                        @szBTypeId, @szKtypeID) bb
                         WHERE  a.KtypeId = bb.KtypeId )
    ORDER BY a.vchcode
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--	得到加盟店配货订单明细
    Getjoinorder:
    SELECT  b.[vchcode],
            b.[vchtype],
            ISNULL(b.[qty], 0) AS Qty,
            ISNULL(b.[tax_total], 0) AS Total,
            b.[date],
            ISNULL(d.[number], '') AS [number],
            ISNULL(d.[summary], '') AS comment,
            b.ptypeid,
            b.btypeid,
            b.ktypeid,
            '' AS redword,
            '' AS redold
    FROM    BakDlyorder b,
            dlyndxorder d
    WHERE   @szBeginData <= b.date
            AND @szEndData >= b.date
            AND b.btypeid LIKE @szbtypeId + '%'
            AND b.ktypeid LIKE @szKtypeId + '%'
            AND b.vchcode = d.vchcode
            AND b.vchtype IN ( 221, 223 )
            AND b.[ptypeId] LIKE @szPtypeId + '%'
    ORDER BY b.[vchcode]
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
-- 	得到自营店配货订单明细
    GetBuyorder:
	
    SELECT  a.[vchcode],
            a.[vchtype],
            -( ISNULL(a.[qty], 0) ) AS Qty,
            ISNULL(a.[tax_total], 0) AS Total,
            a.[date],
            ISNULL(d.[number], '') AS [number],
            ISNULL(d.[summary], '') AS comment,
            a.ptypeid,
            a.btypeid,
            a.ktypeid,
            '' AS redword,
            '' AS redold
    FROM    BakDlyorder a,
            dlyndxorder d
    WHERE   @szBeginData <= a.date
            AND @szEndData >= a.date
            AND a.btypeid LIKE @szbtypeId + '%'
            AND a.ktypeid LIKE @szKtypeId + '%'
            AND a.vchcode = d.vchcode
            AND a.[ptypeId] LIKE @szPtypeId + '%'
            AND a.vchtype IN ( 211, 214 )
    ORDER BY a.[vchcode]
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
    GetBtypeSaleAnalyse:
    SELECT  ds.[vchcode],
            ds.[vchtype],
            SUM(ABS(( CASE WHEN ISNULL(dsd.[qty], 0) > 0
                           THEN ISNULL(dsd.[qty], 0)
                           ELSE 0
                      END ))) AS InStock,
            SUM(ABS(( CASE WHEN ISNULL(dsd.[qty], 0) < 0
                           THEN ISNULL(dsd.[qty], 0)
                           ELSE 0
                      END ))) AS OutStock,
            -SUM(( ISNULL(( dsd.[tax_total] ), 0) )) AS Total,
            ds.[date],
            ISNULL(d.[number], '''') AS [number],
            ds.redold,
            ISNULL(d.[summary], '''') AS comment,
            Ptypeid,
            ds.btypeid,
            ds.Ktypeid,
            ds.RedWord
    FROM    Dlydata ds
            LEFT JOIN dlyndx d ON ds.vchcode = d.vchcode
            LEFT JOIN dlydatadetail dsd ON ds.dlyorder = dsd.dlyorder
    WHERE   ds.BillType = 2
            AND ptypeid LIKE @szPtypeId + '%'
            --AND ds.branchid LIKE @branchid + '%'
            AND ds.usedtype = CASE WHEN ds.vchtype IN ( 222, 224 ) THEN 1
                                ELSE ds.usedtype
                           END
            --AND ds.ktypeid LIKE @szKtypeId + '%'
            AND EXISTS ( SELECT 1 FROM   FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) FilterK WHERE  ds.ktypeId = Filterk.KtypeId )
            AND ds.Dtypeid LIKE @deptid + '%'
            AND ds.etypeid LIKE @szEtypeid + '%'
            AND ( CASE WHEN ds.vchtype IN ( 100, 101 ) THEN ds.ktypeid
                       ELSE ds.Btypeid
                  END ) LIKE @szBtypeid + '%'
            AND ds.date BETWEEN @szBeginData AND @szEndData
    GROUP BY ds.vchcode,
            ds.vchtype,
            ds.[date],
            d.number,
            ds.redold,
            d.summary,
            Ptypeid,
            ds.btypeid,
            ds.Ktypeid,
            ds.RedWord
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
      
    GetRetailSale:
    SELECT  ds.[vchcode],
            ds.[vchtype],
            SUM(ABS(( CASE WHEN ISNULL(dsd.[qty], 0) > 0
                           THEN ISNULL(dsd.[qty], 0)
                           ELSE 0
                      END ))) AS InStock,
            SUM(ABS(( CASE WHEN ISNULL(dsd.[qty], 0) < 0
                           THEN ISNULL(dsd.[qty], 0)
                           ELSE 0
                      END ))) AS OutStock,
            -SUM(( ISNULL(( dsd.[tax_total] ), 0) )) AS Total,
            ds.[date],
            ISNULL(d.[number], '''') AS [number],
            ISNULL(d.[summary], '''') AS comment,
            Ptypeid,
            ds.btypeid,
            ds.Ktypeid,
            ds.redold,
            ds.RedWord
    FROM    Dlydata ds
            LEFT JOIN Btype b ON ds.Btypeid = b.typeid
            LEFT JOIN dlyndx d ON ds.vchcode = d.vchcode
            LEFT JOIN FN_GetPowerRangePList(@OperatorId, '') p ON ds.ptypeid = p.typeid
            LEFT JOIN dlydatadetail dsd ON ds.dlyorder = dsd.dlyorder
    WHERE   ds.vchtype IN ( 12, 13, 100, 101 )
            --AND ds.branchid LIKE @branchid + '%'
            AND p.stop = CASE @ifstop
                           WHEN '1' THEN p.stop
                           ELSE 0
                         END
            AND ds.btypeid LIKE @szBtypeid + '%'
            AND ds.Dtypeid LIKE @deptid + '%'
            AND ( ( ( CASE @CustType
                        WHEN '1' THEN CustValue1
                        WHEN '2' THEN CustValue2
                        WHEN '3' THEN CustValue3
                        WHEN '4' THEN CustValue4
                        WHEN '5' THEN CustValue5
                        ELSE CustValue6
                      END ) IN ( SELECT typeid
                                 FROM   GetResultTableLZL(@SaleTraitName) )
                    AND @CustType <> ''
                  )
                  OR ( @CustType = '' )
                )
            AND ptypeid LIKE @szPtypeId + '%'
           -- AND ds.ktypeid LIKE @szKtypeId + '%'
           AND EXISTS ( SELECT 1 FROM   FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) FilterK WHERE  ds.ktypeId = Filterk.KtypeId )
            AND ds.date BETWEEN @szBeginData AND @szEndData
    GROUP BY ds.vchcode,
            ds.vchtype,
            ds.[date],
            d.number,
            d.summary,
            Ptypeid,
            ds.btypeid,
            ds.Ktypeid,
            ds.redold,
            ds.RedWord
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
      
--	得到销售的明细
    GetSale:
    BEGIN  --销售(包括已经结算的商场专柜零售、退货单)
        SELECT  a.[vchcode],
                a.[vchtype],
                a.ktypeid,
                a.ptypeid,
                a.btypeid,
                SUM(ABS(( CASE WHEN ISNULL(ad.[qty], 0) > 0
                               THEN ISNULL(ad.[qty], 0)
                               ELSE 0
                          END ))) AS InStock,
                SUM(ABS(( CASE WHEN ISNULL(ad.[qty], 0) < 0
                               THEN ISNULL(ad.[qty], 0)
                               ELSE 0
                          END ))) AS OutStock,
                -SUM(ISNULL(ad.[tax_total], 0)) AS Total,
                a.[date],
                SUM(ad.qty) AS cccc,
                a.RedOld,
                a.RedWord
        FROM    Dlydata a,
                FN_GetPowerRangePList(@OperatorId, '') p,
                dlydatadetail ad
        WHERE   billtype = 2
                AND @szBeginData <= [date]
                AND a.ptypeid = p.typeid
                AND a.dlyorder = ad.dlyorder
                --AND a.branchid LIKE @branchid + '%'
                AND EXISTS ( SELECT 1 FROM   FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) FilterK WHERE  a.ktypeId = Filterk.KtypeId )
                AND @szEndData >= [date]
                AND Dtypeid LIKE @deptid + '%'
                AND btypeid LIKE @szBtypeid + '%'
                --AND ktypeid LIKE @szKtypeId + '%'
                AND etypeid LIKE @szetypeid + '%'
                AND ( ( ( CASE @CustType
                            WHEN '1' THEN CustValue1
                            WHEN '2' THEN CustValue2
                            WHEN '3' THEN CustValue3
                            WHEN '4' THEN CustValue4
                            WHEN '5' THEN CustValue5
                            ELSE CustValue6
                          END ) IN ( SELECT typeid
                                     FROM   GetResultTableLZL(@SaleTraitName) )
                        AND @CustType <> ''
                      )
                      OR ( @CustType = '' )
                    )
                AND LEFT(a.[ptypeId], LEN(@szPtypeId + '%')) LIKE @szPtypeId
                + '%'
                AND p.stop = CASE @ifstop
                               WHEN 1 THEN p.stop
                               ELSE 0
                             END
                AND a.usedtype = CASE WHEN vchtype IN ( 222, 224 ) THEN 1
                                    ELSE a.usedtype
                               END
			--and a.vchtype in (11,45,12,13,222,224,100,101,24)  
        GROUP BY a.vchcode,
                vchtype,
                date,
                a.ktypeid,
                a.ptypeid,
                a.btypeid,
                a.RedOld,
                a.RedWord
        ORDER BY a.vchcode
        GOTO succee
    END
   
--加盟店销售统计明细
    GetJoin:
    SELECT  a.[vchcode],
            a.[vchtype],
            a.ktypeid,
            a.ptypeid,
            a.btypeid,
            SUM(ABS(( CASE WHEN ISNULL(a.[qty], 0) > 0 THEN ISNULL(a.[qty], 0)
                           ELSE 0
                      END ))) AS InStock,
            SUM(ABS(( CASE WHEN ISNULL(a.[qty], 0) < 0 THEN ISNULL(a.[qty], 0)
                           ELSE 0
                      END ))) AS OutStock,
            -SUM(ISNULL(a.[tax_total], 0)) AS Total,
            a.[date],
            SUM(qty) AS cccc,
            a.RedOld,
            a.RedWord
    FROM    Dlydata a,
            FN_GetPowerRangePList(@OperatorId, '') p
    WHERE   billtype = 2
            AND @szBeginData <= [date]
            AND a.ptypeid = p.typeid
            AND @szEndData >= [date]
            AND Dtypeid LIKE @deptid + '%'
            AND btypeid LIKE @szBtypeid + '%'
            AND ktypeid LIKE @szKtypeId + '%'
            AND ( ( ( CASE @CustType
                        WHEN '1' THEN CustValue1
                        WHEN '2' THEN CustValue2
                        WHEN '3' THEN CustValue3
                        WHEN '4' THEN CustValue4
                        WHEN '5' THEN CustValue5
                        ELSE CustValue6
                      END ) IN ( SELECT typeid
                                 FROM   GetResultTableLZL(@SaleTraitName) )
                    AND @CustType <> ''
                  )
                  OR ( @CustType = '' )
                )
            AND LEFT(a.[ptypeId], LEN(@szPtypeId + '%')) LIKE @szPtypeId + '%'
            AND p.stop = CASE @ifstop
                           WHEN 1 THEN p.stop
                           ELSE 0
                         END
            AND a.usedtype = CASE WHEN vchtype IN ( 222, 224 ) THEN 1
                                ELSE a.usedtype
                           END
            AND a.vchtype IN ( 222, 224 )
    GROUP BY a.vchcode,
            vchtype,
            date,
            a.ktypeid,
            a.ptypeid,
            a.btypeid,
            a.RedOld,
            a.RedWord
    ORDER BY a.vchcode
    GOTO succee
	
    GetShop:
    BEGIN
        SELECT  a.[vchcode],
                a.[vchtype],
                a.ktypeid,
                a.ptypeid,
                a.btypeid,
                SUM(ABS(( CASE WHEN ISNULL(a.[qty], 0) > 0
                               THEN ISNULL(a.[qty], 0)
                               ELSE 0
                          END ))) AS InStock,
                SUM(ABS(( CASE WHEN ISNULL(a.[qty], 0) < 0
                               THEN ISNULL(a.[qty], 0)
                               ELSE 0
                          END ))) AS OutStock,
                -SUM(ISNULL(a.[tax_total], 0)) AS Total,
                a.[date],
                SUM(qty) AS cccc,
                a.RedOld,
                a.RedWord
        FROM    Dlydata a,
                FN_GetPowerRangePList(@OperatorId, '') p
        WHERE   billtype = 2
                AND @szBeginData <= [date]
                AND a.ptypeid = p.typeid
                AND @szEndData >= [date]
                AND Dtypeid LIKE @deptid + '%'
                AND btypeid LIKE @szBtypeid + '%'
                AND ktypeid LIKE @szKtypeId + '%'
                AND ( ( ( CASE @CustType
                            WHEN '1' THEN CustValue1
                            WHEN '2' THEN CustValue2
                            WHEN '3' THEN CustValue3
                            WHEN '4' THEN CustValue4
                            WHEN '5' THEN CustValue5
                            ELSE CustValue6
                          END ) IN ( SELECT typeid
                                     FROM   GetResultTableLZL(@SaleTraitName) )
                        AND @CustType <> ''
                      )
                      OR ( @CustType = '' )
                    )
                AND LEFT(a.[ptypeId], LEN(@szPtypeId + '%')) LIKE @szPtypeId
                + '%'
                AND p.stop = CASE @ifstop
                               WHEN 1 THEN p.stop
                               ELSE 0
                             END
                AND a.vchtype IN ( 100, 101 )
        GROUP BY a.vchcode,
                vchtype,
                date,
                a.ktypeid,
                a.ptypeid,
                a.btypeid,
                a.RedOld,
                a.RedWord
        ORDER BY a.vchcode
        GOTO succee
        IF @@rowcount = 0 
            GOTO error2
        GOTO succee
    END
	
    GetSalepreferential:
    IF ( @nBSonnum > 0 )
        OR ( @neSonnum > 0 ) 
        BEGIN
            SELECT  S.vchCode,
                    s.vchtype,
                    s.Date,
                    s.bTypeID,
                    s.eTypeID,
                    ISNULL(n.[summary], '') AS comment,
                    n.Number,
                    ISNULL(SUM(a.Total), 0) AS yTotal,
                    ISNULL(SUM(-s.Tax_Total), 0) AS TaxTotal,
                    ISNULL(SUM(-s.Tax_Total) - SUM(a.Total), 0) AS Total,
                    n.Number,
                    ISNULL(b.FullName, '') AS bfullName,
                    ISNULL(e.FullName, '') AS efullName,
                    s.RedOld,
                    s.RedWord
            FROM    ( SELECT    vchcode,
                                vchtype,
                                date,
                                btypeid,
                                etypeid,
                                SUM(Tax_Total) AS Tax_Total,
                                redold,
                                redword
                      FROM      Dlydata
                      WHERE     Date >= @szBeginData
                                AND Date <= @szEndData
                                AND BTypeID LIKE @szBTypeID + '%'
                                AND ETypeID LIKE @szETypeID + '%'
                                AND KTypeID LIKE @szKTypeID
                      GROUP BY  vchcode,
                                vchtype,
                                date,
                                btypeid,
                                etypeid,
                                redword,
                                redold
                    ) AS S
                    LEFT OUTER JOIN ( SELECT    VchCode,
                                                Total
                                      FROM      DlyA
                                      WHERE     ATypeID = '000040000100004'
                                                AND VchType IN ( 24, 222, 224, 11, 45, 12, 13 )
                                                AND Date >= @szBeginData
                                                AND Date <= @szEndData
                                                AND BTypeID LIKE @szBTypeID
                                                + '%'
                                                AND ETypeID LIKE @szETypeID
                                                + '%'
                                    ) AS a ON s.VchCode = A.VchCode
                    LEFT OUTER JOIN DlyNdx n ON s.VchCode = n.VchCode
                    LEFT OUTER JOIN BType b ON s.BTypeID = b.TypeID
                    LEFT OUTER JOIN Employee e ON s.ETypeID = e.TypeID
            WHERE   s.BTypeID LIKE @szBTypeID + '%'
                    AND s.ETypeID LIKE @szETypeID + '%'
            GROUP BY s.vchCode,
                    s.vchtype,
                    s.Date,
                    s.bTypeID,
                    s.eTypeID,
                    n.summary,
                    n.Number,
                    b.fullName,
                    e.fullName,
                    s.RedOld,
                    s.RedWord
            ORDER BY S.vchcode
        END
    ELSE 
        BEGIN
            SELECT  s.vchCode,
                    s.vchtype,
                    s.Date,
                    s.bTypeID,
                    s.eTypeID,
                    ISNULL(n.[summary], '') AS comment,
                    ISNULL(SUM(a.Total), 0) AS yTotal,
                    ISNULL(SUM(-s.Tax_Total), 0) AS TaxTotal,
                    ISNULL(SUM(-s.Tax_Total) - SUM(a.Total), 0) AS Total,
                    n.Number,
                    n.Summary,
                    ISNULL(b.FullName, '') AS bfullName,
                    ISNULL(e.FullName, '') AS efullName,
                    s.RedOld,
                    s.RedWord
            FROM    ( SELECT    vchcode,
                                vchtype,
                                date,
                                btypeid,
                                etypeid,
                                SUM(Tax_Total) AS Tax_Total,
                                RedOld,
                                RedWord
                      FROM      dlydata
                      WHERE     Date >= @szBeginData
                                AND Date <= @szEndData
                                AND BTypeID LIKE @szBTypeID + '%'
                                AND ETypeID LIKE @szETypeID + '%'
                      GROUP BY  vchcode,
                                vchtype,
                                date,
                                btypeid,
                                etypeid,
                                RedOld,
                                RedWord
                    ) s
                    LEFT OUTER JOIN ( SELECT    VchCode,
                                                Total
                                      FROM      DlyA
                                      WHERE     ATypeID = '000040000100004'
                                                AND VchType IN ( 24, 222, 224, 11, 45, 12, 13 )
                                                AND Date >= @szBeginData
                                                AND Date <= @szEndData
                                                AND BTypeID LIKE @szBTypeID
                                                AND ETypeID LIKE @szETypeID
                                    ) a ON a.VchCode = s.VchCode
                    LEFT OUTER JOIN DlyNdx n ON s.VchCode = n.VchCode
                    LEFT OUTER JOIN BType b ON s.BTypeID = b.TypeID
                    LEFT OUTER JOIN Employee e ON s.ETypeID = e.TypeID
            GROUP BY s.vchCode,
                    s.vchtype,
                    s.Date,
                    s.bTypeID,
                    s.eTypeID,
                    n.[summary],
                    n.Number,
                    s.RedOld,
                    s.RedWord,
                    b.fullName,
                    e.fullName
            ORDER BY s.vchcode
        END
    IF @@ROWCOUNT = 0 
        GOTO error2
    GOTO succee
	
    GetExp:
    IF @szPtypeId = 'B' 
        SELECT  @szEtypeid = ''
    IF @szPtypeid = 'E' 
        SELECT  @szBtypeid = ''
    SELECT  a.[vchcode],
            a.[vchtype],
            a.[atypeid],
            a.[date],
            b.redold,
            a.[Total],
            ISNULL(b.[number], '') AS number,
            ISNULL(b.[summary], '') AS comment,
            a.btypeid,
            a.ktypeid,
            b.[redold],
            b.RedWord,
            b.etypeid
    FROM    ( SELECT    *
              FROM      DlyA
              WHERE     Date >= @szBeginData
                        AND Date <= @szendData
                        AND LEFT([atypeId], LEN(@Business_EXPENSE_ID)) LIKE @Business_EXPENSE_ID
                        + '%'
                        AND LEFT([etypeId], LEN(@szetypeid)) LIKE @szetypeid
                        + '%'
                        AND LEFT([btypeId], LEN(@szbtypeId)) LIKE @szbtypeId
                        + '%'
            ) a
            LEFT JOIN --and Left([btypeId], Len(@szbtypeId)) like @szbtypeId+'%') a,
            ( SELECT    *
              FROM      DlyNdx
              WHERE     [date] >= @szBeginData
                        AND Date <= @szendData
            ) b ON a.vchcode = b.vchcode
    ORDER BY a.[vchcode]
    IF @@ROWCOUNT = 0 
        GOTO error2
    GOTO succee

    succee:
    RETURN 0
    error1:
    SELECT  'A'
    RETURN -103
    error2:
    SELECT  'B'
    RETURN -101




GO
 SET QUOTED_IDENTIFIER OFF 
GO
 SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZQueryRetailDateSale]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
  DROP PROCEDURE [dbo].[FZQueryRetailDateSale]
GO



--  ********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：QueryEtypeSale                       
--  ||   过程功能：取得职员、往来单位的销售、回款，和职员的应收应付等统计信息  
--  ||=========================================================================================  
--  ||   参数说明：  参数名称         类型            意义                     输入输出  
--  ||            -----------------------------------------------------------------------------  
--  ||           @sztypeid              varchar(50),        职员Id  
--  ||           @Startdate             varchar(10),        开始时间  
--  ||           @Enddate               varchar(10),        结束时间  
--  ||=========================================================================================     
--  ||   返回值：         值                                     说明  
--  ||       ----------------------------------------------------------------------------------------  
--  ||               
--  ||==========================================================================================  
CREATE    PROCEDURE FZQueryRetailDateSale
  (
    @ptypeid VARCHAR(50) ,
    @Etypeid VARCHAR(50) ,
    @Ktypeid VARCHAR(2000) ,
    @Btypeid VARCHAR(50) ,
    @szStartDate VARCHAR(10) ,
    @szEndDate VARCHAR(10) ,
    @branchid VARCHAR(2000) ,
    @OperatorId VARCHAR(50) = ''		  
  )
AS /* 
 Declare @szparid varchar(50)  

 if @Btypeid is null or  @Btypeid=''   
  	set @szparid='00000'  
 else  
  	set @szparid=@Btypeid  
 */
 
	--定义小数位数变量并获取其自定义值
	DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
	EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
	
  IF @branchid IS NULL 
    SET @branchid = ''  
 
  SELECT  [Date] ,
          SUM(-qty) AS qty ,
          SUM(-BargainTotal) AS Total ,
          -SUM(TaxTotal) AS TaxTotal ,
          SUM(-Tax_Total) AS Tax_Total ,
          SUM(-Salemoney) AS SaleMoney , --新增销售金额查询 2011-7-4 15:39:43 hww
          SUM(-BargainTotal) AS BargainTotal ,
          SUM(-Salemoney) - SUM(-Tax_Total) AS DeductTotal ,
          ROUND(SUM(-qty * ISNULL(p.RetailPrice, 0)),@dig_total) AS RetailTotal ,
          SUM(-CostTotal) AS CostTotal ,
          SUM(-Total) - SUM(-CASE WHEN vchtype IN ( 100, 101 ) THEN salemoney
                                  ELSE bargaintotal
                             END) AS ConvertTotal ,
          ( SUM(ISNULL(-BargainTotal, 0)) - SUM(-ISNULL(CostTotal, 0)) ) AS Profittotal ,
          CAST(ROUND(SUM(-ISNULL(Total - CASE WHEN vchtype IN ( 100, 101 ) THEN salemoney
                                             ELSE bargaintotal
                                        END, 0)) / ( CASE SUM(-ISNULL(Total, 0))
                                                       WHEN 0 THEN 1
                                                       ELSE SUM(-ISNULL(Total, 0))
                                                     END ) * 100,@dig_rate) AS VARCHAR(24))  AS RLrate ,
          SUM(-d.Total) AS DiscountTotal
  FROM    Dlydata d LEFT JOIN dbo.Ptype p ON p.TypeID = d.PtypeId
  WHERE   d.vchtype IN ( 13, 12, 100, 101 )
          AND redold = 'F'
 	 
       and ptypeid like @Ptypeid+'%'  
       and Etypeid like @Etypeid+'%'
       and btypeid like @Btypeid+'%'  	 

          AND EXISTS ( SELECT 1
                       FROM   FN_GetPowerRangePList(@OperatorId, @PtypeID) FilterP
                       WHERE  d.PtypeId = FilterP.TypeId )
          AND EXISTS ( SELECT 1
                       FROM   FN_GetPowerRangeBList(@OperatorId, @BtypeID, '2,3,4,6') FilterB
                       WHERE  d.BtypeId = FilterB.TypeId )
          AND EXISTS ( SELECT 1
                       FROM   FN_GetPowerRangeEList(@OperatorId, @EtypeID) FilterE
                       WHERE  d.EtypeId = FilterE.TypeId )
          AND EXISTS ( SELECT 1
                       FROM   FN_GetStockListOfBranch(@OperatorID, @BranchId, @Ktypeid) FilterK
                       WHERE  d.ktypeId = Filterk.KtypeId )
          AND [date] BETWEEN @szStartDate AND @szEndDate
  GROUP BY [Date]  
      

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZQueryRetailDateSaleDetail]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZQueryRetailDateSaleDetail]
GO



--  ********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：QueryRetailDateSaleDetail                  
--  ||   过程功能：取得零售销售统计信息  
--  ||=========================================================================================  
--  ||   参数说明：  参数名称         类型            意义                     输入输出  
--  ||            -----------------------------------------------------------------------------  
--  ||     @ptypeid  varchar(50),  
--  ||     @Etypeid  varchar(50),  
--  ||     @Ktypeid  varchar(50),  
--  ||     @Btypeid  varchar(50),  
--  ||     @szStartDate             varchar(10),        开始时间  
--  ||     @szEndDate               varchar(10),        结束时间  
--  ||     @type    varchar(1)      'Z' 总量，'L'列表,'M'明细  
--  ||=========================================================================================     
--  ||   返回值：         值                                     说明  
--  ||       ----------------------------------------------------------------------------------------  
--  ||               
--  ||==========================================================================================  
CREATE    PROCEDURE FZQueryRetailDateSaleDetail
    (
      @ptypeid VARCHAR(50),
      @Etypeid VARCHAR(50),
      @Ktypeid VARCHAR(2000),
      @Btypeid VARCHAR(50),
      @szStartDate VARCHAR(10),
      @szEndDate VARCHAR(10),
      @type VARCHAR(1),
      @Branchid VARCHAR(2000),
      @OperatorId VARCHAR(50) = '00000'  
    )
AS 

--定义小数位数变量并获取其自定义值
DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 

--设置变量用于操作员拥有所有多级权限时，优化查询
DECLARE @PowerRangeP BIT --商品
DECLARE @PowerRangeE BIT --职员
DECLARE @PowerRangeA BIT --科目
DECLARE @PowerRangeB BIT --客户
DECLARE @PowerRangeC BIT --机构
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 0 AND TypeID = '00000') SET @PowerRangeP = 1 ELSE SET @PowerRangeP = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 1 AND TypeID = '00000') SET @PowerRangeE = 1 ELSE SET @PowerRangeE = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 3 AND TypeID = '00000') SET @PowerRangeA = 1 ELSE SET @PowerRangeA = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 4 AND TypeID = '00000') SET @PowerRangeB = 1 ELSE SET @PowerRangeB = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 5 AND TypeID = '00000') SET @PowerRangeC = 1 ELSE SET @PowerRangeC = 0

    DECLARE @szparid VARCHAR(50)  
    IF @ptypeid IS NULL
        OR @ptypeid = '' 
        SET @szparid = '00000'  
    ELSE 
        SET @szparid = @ptypeid  

    IF @branchid IS NULL 
        SET @branchid = ''  

    IF @type = 'Z' 
        BEGIN  
            SELECT  p.typeid AS ptypeid,
                    ISNULL(SUM(s.qty), 0) AS qty,
                    ISNULL(SUM(s.BargainTotal), 0) AS Total, --Total取 不含税金额  
                    ISNULL(SUM(s.BargainTotal), 0) AS BargainTotal,
                    ISNULL(SUM(s.tax_total), 0) AS Tax_total,
                    ISNULL(SUM(s.ConvertTotal), 0) AS convertTotal,
                    ISNULL(SUM(s.TaxTotal), 0) AS TaxTotal,
                    ISNULL(SUM(s.DeductTotal), 0) AS DeductTotal,
                    ROUND(ISNULL(SUM(s.RetailTotal), 0),@dig_total) AS RetailTotal,
                    ISNULL(SUM(s.Costtotal), 0) AS CostTotal,
                    ISNULL(SUM(s.Profittotal), 0) AS Profittotal,
                    ISNULL(CAST(ROUND(SUM(s.Rlrate),@dig_rate) AS VARCHAR(24)), '') AS Rlrate,
                    p.Retailprice,
                    ISNULL(SUM(s.DiscountTotal), 0) AS DiscountTotal
            FROM    ( SELECT    [typeid],
                                porder,
                                retailprice
                      FROM      FN_GetPowerRangePTree(@OperatorId, @Ptypeid) p --ptype p  
                      WHERE     deleted = 0
                                AND [typeid] <> '00000'
                                AND ( [parid] = @szparid
                                      OR ( typeid = @PtypeId
                                           AND sonnum = 0
                                         )
                                    )
                    ) p
                    LEFT JOIN ( SELECT  SUBSTRING(d.ptypeid, 1,
                                                  LEN(@ptypeid) + 5) AS Ptypeid,
                                        SUM(-qty) AS qty,
                                        SUM(-Salemoney) AS Total,
                                        SUM(-BargainTotal) AS BargainTotal,
                                        -SUM(TaxTotal) AS TaxTotal,
                                        SUM(-Tax_Total) AS Tax_Total,
                                        SUM(-Salemoney) - SUM(-Tax_Total) AS DeductTotal,
                                        SUM(-CostTotal) AS CostTotal,
                                        SUM(-Total)
                                        - SUM(-CASE WHEN vchtype IN ( 100, 101 )
                                                    THEN salemoney
                                                    ELSE bargaintotal
                                               END) AS ConvertTotal,
                                        ( SUM(ISNULL(-BargainTotal, 0))
                                          - SUM(-ISNULL(CostTotal, 0)) ) AS Profittotal,
                                        ROUND(SUM(-ISNULL(Total
                                                    - CASE WHEN vchtype IN ( 100, 101 )
                                                           THEN salemoney
                                                           ELSE bargaintotal
                                                      END, 0))
                                        / ( CASE SUM(-ISNULL(Total, 0))
                                              WHEN 0 THEN 1
                                              ELSE SUM(-ISNULL(Total, 0))
                                            END ) * 100,@dig_rate) AS RLrate,
                                        ROUND(SUM(-qty * p.retailprice),@dig_total) AS RetailTotal,
                                        SUM(-Total) AS DiscountTotal
                                FROM    DlyData d,
                                        ptype p
                                WHERE   d.vchtype IN ( 13, 12, 100, 101 )
                                        AND d.ptypeid = p.typeid
                                        AND d.BillType = 2  
                                        AND EXISTS ( SELECT 1
                                                     FROM   FN_GetPowerRangePList(@OperatorId, @PtypeID) FilterP
                                                     WHERE  d.PtypeId = FilterP.TypeId )
                                        AND EXISTS ( SELECT 1
                                                     FROM   FN_GetPowerRangeBList(@OperatorId, @BtypeID, '2,3,4,6') FilterB
                                                     WHERE  d.BtypeId = FilterB.TypeId )
                                        AND EXISTS ( SELECT 1
                                                     FROM   FN_GetPowerRangeEList(@OperatorId, @EtypeID) FilterE
                                                     WHERE  d.EtypeId = FilterE.TypeId )
                                        AND EXISTS ( SELECT 1
                                                     FROM   FN_GetStockListOfBranch(@OperatorID, @BranchId, @Ktypeid) FilterK
                                                     WHERE  d.ktypeId = Filterk.KtypeId )
                                        AND [date] BETWEEN @szStartDate AND @szEndDate
                                GROUP BY SUBSTRING(d.ptypeid, 1,
                                                   LEN(@ptypeid) + 5)
                              ) s ON s.ptypeid = p.typeid
            GROUP BY [typeid],
                    p.porder,
                    p.Retailprice  
        END  
    IF @type = 'L' 
        BEGIN  
   
            SELECT  p.typeid AS ptypeid,
                    ISNULL(SUM(-qty), 0) AS qty,
                    ISNULL(SUM(-BargainTotal), 0) AS Total, --Total取 不含税金额  
                    ISNULL(SUM(-BargainTotal), 0) AS BargainTotal,
                    -ISNULL(SUM(TaxTotal), 0) AS TaxTotal,
                    ISNULL(SUM(-Tax_Total), 0) AS Tax_Total,
                    ISNULL(SUM(-Salemoney), 0) - ISNULL(SUM(-Tax_Total), 0) AS DeductTotal,  
                    ROUND(ISNULL(SUM(-qty * ISNULL(RetailPrice, 0)), 0),@dig_total) AS RetailTotal,
                    ISNULL(SUM(-CostTotal), 0) AS CostTotal,
                    ISNULL(SUM(-Total), 0)
                    - ISNULL(SUM(-CASE WHEN vchtype IN ( 100, 101 )
                                       THEN salemoney
                                       ELSE bargaintotal
                                  END), 0) AS ConvertTotal,
                    ( SUM(ISNULL(-BargainTotal, 0)) - SUM(-ISNULL(CostTotal, 0)) ) AS Profittotal,
                    CAST(ROUND(SUM(-ISNULL(Total
                                          - CASE WHEN vchtype IN ( 100, 101 )
                                                 THEN salemoney
                                                 ELSE bargaintotal
                                            END, 0))
                    / ( CASE SUM(-ISNULL(Total, 0))
                          WHEN 0 THEN 1
                          ELSE SUM(-ISNULL(Total, 0))
                        END ) * 100,@dig_rate) AS VARCHAR(24))  AS RLrate,
                    Retailprice,
                    ISNULL(SUM(-total), 0) AS DiscountTotal
            FROM    ( SELECT    typeid,
                                Retailprice
                      FROM      FN_GetPowerRangePList(@OperatorId, @PtypeID)--Ptype 
                      WHERE     sonnum = 0
                                AND deleted = 0 --and typeid like @Ptypeid+'%'
                      
                    ) p
                    LEFT JOIN ( SELECT  qty,
                                        ptypeid,
                                        ktypeid,
                                        btypeid,
                                        etypeid,
                                        salemoney,
                                        total,
                                        bargaintotal,
                                        TaxTotal,
                                        Tax_total,
                                        vchtype,
                                        CostTotal
                                FROM    DlyData
                                WHERE   vchtype IN ( 13, 12, 100, 101 )
                                        AND BillType = 2
                                        AND EXISTS ( SELECT 1
                                                     FROM   FN_GetPowerRangePList(@OperatorId, @PtypeID) FilterP
                                                     WHERE  DlyData.PtypeId = FilterP.TypeId )
                                        AND EXISTS ( SELECT 1
                                                     FROM   FN_GetPowerRangeBList(@OperatorId, @BtypeID, '2,3,4,6') FilterB
                                                     WHERE  DlyData.BtypeId = FilterB.TypeId )
                                        AND EXISTS ( SELECT 1
                                                     FROM   FN_GetPowerRangeEList(@OperatorId, @EtypeID) FilterE
                                                     WHERE  DlyData.EtypeId = FilterE.TypeId )
                                        AND EXISTS ( SELECT 1
                                                     FROM   FN_GetStockListOfBranch(@OperatorID, @BranchId, @Ktypeid) FilterK
                                                     WHERE  DlyData.ktypeId = Filterk.KtypeId )
                                        AND [date] BETWEEN @szStartDate AND @szEndDate
                              ) d ON d.ptypeid = p.typeid
            GROUP BY typeid,
                    Retailprice  
        END  
    IF @type = 'M' 
        BEGIN  
            SELECT  ptypeid,
                    ISNULL(SUM(-dd.qty), 0) AS qty,
                    ISNULL(SUM(-dd.BargainTotal), 0) AS Total, --Total取 不含税金额  
                    ISNULL(SUM(-dd.BargainTotal), 0) AS BargainTotal,
                    ISNULL(SUM(-dd.TaxTotal), 0) TaxTotal,
                    ISNULL(SUM(-dd.Tax_Total), 0) Tax_Total,
                    ISNULL(SUM(-dd.Salemoney), 0) - ISNULL(SUM(-dd.Tax_Total),
                                                           0) AS DeductTotal,  
                    ROUND(ISNULL(SUM(-dd.qty * ISNULL(p.RetailPrice, 0)), 0),@dig_total) AS RetailTotal,
                    ISNULL(SUM(-dd.CostTotal), 0) AS CostTotal,
                    ISNULL(SUM(-dd.Total), 0) AS DiscountTotal,
                    ISNULL(SUM(-dd.Total), 0)
                    - ISNULL(SUM(-CASE WHEN vchtype IN ( 100, 101 )
                                       THEN dd.salemoney
                                       ELSE dd.bargaintotal
                                  END), 0) AS ConvertTotal,
                    ( SUM(ISNULL(-dd.BargainTotal, 0))
                      - SUM(-ISNULL(dd.CostTotal, 0)) ) AS Profittotal,
                    CAST(ROUND(SUM(-ISNULL(dd.Total
                                          - CASE WHEN vchtype IN ( 100, 101 )
                                                 THEN dd.salemoney
                                                 ELSE dd.bargaintotal
                                            END, 0))
                    / ( CASE SUM(-ISNULL(dd.Total, 0))
                          WHEN 0 THEN 1
                          ELSE SUM(-ISNULL(dd.Total, 0))
                        END ) * 100,@dig_rate) AS VARCHAR(24))  AS RLrate,
                    p.Retailprice,
                    RIGHT('00000' + CAST(p.colorid AS VARCHAR), 5) AS pctypeid,
                    RIGHT('00000' + CAST(p.sizeid AS VARCHAR), 5) AS pstypeid
            FROM    DlyData d,
                    ( SELECT    typeid,
                                b.colorid,
                                c.sizeid,RetailPrice
                      FROM      FN_GetPowerRangePList(@OperatorId, @PtypeID) p
                                LEFT JOIN ptypecolor b ON p.typeid = b.ptypeid
                                LEFT JOIN ptypesize c ON p.typeid = C.ptypeid
                    ) p,
                    DlyDatadetail dd
            WHERE   [date] BETWEEN @szStartDate AND @szEndDate
					AND d.vchtype IN ( 13, 12, 100, 101 )
                    AND d.BillType = 2
                    AND d.dlyorder = dd.dlyorder
                    AND dd.sizeid = p.sizeid
                    AND dd.colorid = p.colorid
                    AND d.ptypeid = p.typeid  
                    AND ((1=@PowerRangeP and d.PtypeId LIKE @PtypeID + '%') OR EXISTS ( SELECT 1
                                 FROM   FN_GetPowerRangePList(@OperatorId, @PtypeID) FilterP
                                 WHERE  d.PtypeId = FilterP.TypeId ))
                    AND ((1=@PowerRangeB and d.BtypeId LIKE @BtypeID + '%') OR EXISTS ( SELECT 1
                                 FROM   FN_GetPowerRangeBList(@OperatorId, @BtypeID, '2,3,4,6') FilterB
                                 WHERE  d.BtypeId = FilterB.TypeId ))
                    AND ((1=@PowerRangeE and d.EtypeId LIKE @EtypeID + '%') OR EXISTS ( SELECT 1
                                 FROM   FN_GetPowerRangeEList(@OperatorId, @EtypeID) FilterE
                                 WHERE  d.EtypeId = FilterE.TypeId ))
                    AND EXISTS ( SELECT 1                                                     
                                 FROM   FN_GetStockListOfBranch(@OperatorID, @BranchId, @Ktypeid) FilterK
                                 WHERE  d.ktypeId = Filterk.KtypeId )
                    AND d.BranchId LIKE @BranchId + '%'
            GROUP BY Ptypeid,
                    p.Retailprice,
                    p.sizeid,
                    p.colorid
--             HAVING  ABS(SUM(-dd.qty)) + ABS(SUM(ISNULL(-dd.Salemoney, 0))) + ABS(ISNULL(SUM(-dd.Salemoney), 0) - ISNULL(SUM(-dd.Tax_Total), 0)) + ABS(SUM(-dd.TaxTotal)) <> 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 1
           FROM   dbo.sysobjects
           WHERE  id = object_id(N'[dbo].[FZQueryRetailSaleListCS_BS]')
                  AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
  DROP PROCEDURE [dbo].[FZQueryRetailSaleListCS_BS]

GO

CREATE PROCEDURE FZQueryRetailSaleListCS_BS (
  @szPtypeId     VARCHAR(50),
  @szKtypeid     VARCHAR(2000),
  @szBtypeid     VARCHAR(50),
  @szBeginData   VARCHAR(50),
  @szEndData     VARCHAR(50),
  @ifstop        VARCHAR(2),
  @attrib1       INT =-1,
  @attrib2       INT =-1,
  @attrib3       INT =-1,
  @attrib4       INT =-1,
  @Assist1TypeID INT =-1,
  @Assist2TypeID INT =-1,
  @Assist3TypeID INT =-1,
  @Assist4TypeID INT =-1,
  @Sizeid        VARCHAR(4)='',
  @Colorid       VARCHAR(4)='',
  @SaleTraitName VARCHAR(1000),
  @branchid      VARCHAR(2000),
  @OperatorId    VARCHAR(50)='',
  @ifxiaopiao VARCHAR(2),  --是否包含未过账小票（1：是，0：否）
  @ifdraft VARCHAR(2)      --是否包含零售单草稿（1：是，0：否）
)
AS
       --设置变量用于操作员拥有所有多级权限时，优化查询
    DECLARE @PowerRangeP BIT --商品
    DECLARE @PowerRangeE BIT --职员
    DECLARE @PowerRangeA BIT --科目
    DECLARE @PowerRangeB BIT --客户
    DECLARE @PowerRangeC BIT --机构
    IF EXISTS (SELECT 1 FROM   UserPowerRange WHERE  EtypeID = @OperatorId AND BaseType = 0 AND TypeID = '00000') SET @PowerRangeP = 1 ELSE SET @PowerRangeP = 0
    IF EXISTS (SELECT 1 FROM   UserPowerRange WHERE  EtypeID = @OperatorId AND BaseType = 1 AND TypeID = '00000') SET @PowerRangeE = 1 ELSE SET @PowerRangeE = 0
    IF EXISTS (SELECT 1 FROM   UserPowerRange WHERE  EtypeID = @OperatorId AND BaseType = 3 AND TypeID = '00000') SET @PowerRangeA = 1 ELSE SET @PowerRangeA = 0
    IF EXISTS (SELECT 1 FROM   UserPowerRange WHERE  EtypeID = @OperatorId AND BaseType = 4 AND TypeID = '00000') SET @PowerRangeB = 1 ELSE SET @PowerRangeB = 0
    IF EXISTS (SELECT 1 FROM   UserPowerRange WHERE  EtypeID = @OperatorId AND BaseType = 5 AND TypeID = '00000') SET @PowerRangeC = 1 ELSE SET @PowerRangeC = 0

    DECLARE @tempPtypeid VARCHAR(50)
    SET @tempPtypeid=@szPtypeId
    IF @branchid IS NULL
      SET @branchid=''
    IF @szPtypeId IS NULL OR @szPtypeId = ''
      SET @szPtypeId='%'
    IF @Colorid IS NULL OR @Colorid = '' OR @Colorid = '0'
      SET @Colorid='%'
    IF @Sizeid IS NULL OR @Sizeid = '' OR @Sizeid = '0'
      SET @Sizeid='%'
      
IF OBJECT_ID('tempdb..#FilterB','U') IS NOT NULL   
DROP TABLE #FilterB  
IF OBJECT_ID('tempdb..#FilterE','U') IS NOT NULL   
DROP TABLE #FilterE  
--IF OBJECT_ID('tempdb..#FilterP','U') IS NOT NULL   
--DROP TABLE #FilterP  
IF OBJECT_ID('tempdb..#FilterK','U') IS NOT NULL   
DROP TABLE #FilterK  
CREATE TABLE #FilterB (TypeId VARCHAR(50))    
CREATE TABLE #FilterE (TypeId VARCHAR(50))    
--CREATE TABLE #FilterP (TypeId VARCHAR(50),PORDER INT)    
CREATE TABLE #FilterK (KtypeId VARCHAR(50))      
INSERT  #FilterB(TypeId) SELECT  TypeId FROM  FN_GetPowerRangeBList(@OperatorId, @szBtypeid, '2,3,4,6')     
INSERT  #FilterE(TypeId) SELECT  TypeId FROM  FN_GetPowerRangeEList(@OperatorId, '') 
INSERT  #FilterK(KtypeId) SELECT  KtypeId FROM  FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) 

--取小数位精度配置
DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output

    IF object_id('tempdb..#table_P') IS NOT NULL
      DROP TABLE #table_P

    IF object_id('tempdb..#tmp_data') IS NOT NULL
      DROP TABLE #tmp_data

    IF @SaleTraitName = '全部'
      SET @SaleTraitName=''

IF OBJECT_ID('tempdb..#tmp_data') IS NOT NULL 
   DROP TABLE #tmp_data
 
CREATE TABLE #tmp_data   --创建临时表
(
ptypeid VARCHAR(50),
Qty  numeric(24,10),
S_Tax_total  numeric(24,10),
TQty  numeric(24,10),
T_Tax_total  numeric(24,10),
Taxtotal  numeric(24,10),
SaleMoney  numeric(24,10),
tax_total  numeric(24,10),
colorid INT,
sizeid  INT,
vchtype INT
)

INSERT INTO #tmp_data
            Select	 Ptypeid,
           dd.[qty]       AS [Qty],
           dd.[Tax_total] AS S_Tax_total,
           dd.[qty]       AS [TQty],
           dd.[Tax_total] AS T_Tax_total,
           dd.[taxtotal]  AS Taxtotal,
           dd.[salemoney] AS SaleMoney,
           dd.[tax_total] AS Tax_total,
           dd.colorid,
           dd.sizeid ,
           s.Vchtype
    FROM   dlydata S,
           DlyDataDetail dd
    WHERE  s.vchtype IN(12, 100)
           AND s.[date] BETWEEN @szBeginData AND @szEndData
           AND s.dlyorder = dd.dlyorder
           AND s.billtype = 2
           AND s.redold = 'F'
           AND CAST(dd.sizeid AS VARCHAR(4)) LIKE @Sizeid
           AND CAST(dd.colorid AS VARCHAR(4)) LIKE @Colorid
           AND ((1 = @PowerRangeB
                 AND s.BtypeId LIKE @szBtypeid + '%')
                 OR EXISTS(SELECT 1
                           FROM   #FilterB FilterB
                           WHERE  s.BtypeId = FilterB.TypeId))
           AND ((1 = @PowerRangeE)
                 OR EXISTS(SELECT 1
                           FROM   #FilterE FilterE
                           WHERE  s.EtypeId = FilterE.TypeId))
           AND EXISTS(SELECT 1 FROM   #FilterK FilterK WHERE  s.ktypeId = Filterk.KtypeId)
           AND (CustValue1 LIKE '%' + @SaleTraitName + '%'
                 OR CustValue2 LIKE '%' + @SaleTraitName + '%'
                 OR CustValue3 LIKE '%' + @SaleTraitName + '%'
                 OR CustValue4 LIKE '%' + @SaleTraitName + '%'
                 OR CustValue5 LIKE '%' + @SaleTraitName + '%'
                 OR CustValue6 LIKE '%' + @SaleTraitName + '%')

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


IF  @ifdraft=1  --统计包含零售单草稿
BEGIN 
INSERT INTO #tmp_data
            Select	b.Ptypeid,
			-bd.[qty]      		AS Qty, 	
			-bd.[tax_total]  	As S_Tax_total,  
			-bd.[qty]		    AS TQty,   		
			-bd.[tax_total]		AS T_Tax_total, 	
			-bd.[taxtotal] 		AS Taxtotal,			
			-bd.[salemoney]   	AS SaleMoney,
			-bd.[tax_total]   	AS tax_total,
             bd.[colorid] ,
             bd.[sizeid],
             b.vchtype

    FROM    Bakdly b, BakDlyDetail bd
    WHERE   b.[date] BETWEEN @szBeginData AND @szEndData
	    AND b.vchtype IN ( 12, 100)
	    AND b.Ptypeid<>''
            AND b.dlyorder = bd.dlyorder           
            and ((1=@PowerRangeB AND b.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where b.BtypeId = FilterB.TypeId))  
            and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where b.EtypeId = FilterE.TypeId))  
            and exists(select 1  from #FilterK FilterK where b.ktypeId = Filterk.KtypeId) 	
            AND ( CustValue1 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue2 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue3 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue4 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue5 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue6 LIKE '%' + @SaleTraitName + '%'
                )
END

IF  @ifxiaopiao=1  AND @SaleTraitName = ''--统计包含未过账小票
BEGIN

INSERT INTO #tmp_data
            Select	
             PSL.Ptypeid,
			-SUM(PSL.[qty])  AS Qty, 	
			-SUM(PSL.[total])  As S_Tax_total,  
			-SUM(PSL.[qty])	AS TQty,   		
			-SUM(PSL.[total])	AS T_Tax_total, 	
			        0   AS Taxtotal,			
			-SUM(PSL.[total])  AS SaleMoney,
			-SUM(PSL.[total])  AS tax_total,
		         PSL.[colorid] ,
		         PSL.[sizeid],
		         vchtype=12 --POS过账后默认为零售单
    FROM    dbo.tpx_SaleList PSL,dbo.tpx_SaleIndex PSI
    WHERE   PSI.[Saledate] BETWEEN @szBeginData AND @szEndData
	        AND PSL.Ptypeid<>''
            AND PSL.ZBKeyId=PSI.keyId           
            and ((1=@PowerRangeB AND PSI.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where PSI.BtypeId = FilterB.TypeId))  
            and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where PSI.Salesman = FilterE.TypeId))  
            and exists(select 1  from #FilterK FilterK where PSI.ktypeId = Filterk.KtypeId)
            AND PSI.Draft=0 --Draft 结存标志[0-POS小票,1-草稿] 
            GROUP BY PSL.Ptypeid,PSL.[colorid],PSL.[SizeID]
       
END




    ------------------------------------------------------
    SELECT p.[typeid],
           p.porder,
           isnull([Qty], 0)       AS [Qty],
           isnull(S_Tax_total, 0) AS S_Tax_total,
           isnull(Tqty, 0)        AS Tqty,
           isnull(T_Tax_total, 0) AS T_Tax_total,
           isnull([SaleMoney], 0) AS [SaleMoney],
           isnull([taxtotal], 0)  AS Taxtotal,
           isnull([tax_total], 0) AS Tax_total,
           p.RetailPrice,
           p.sizeid,
           p.colorid
    INTO   #table_P
    FROM   (SELECT p1.[typeid],
                   c.sizeid,
                   b.colorid,
                   porder,
                   retailprice
            FROM   (SELECT p1.[typeid],
                           porder,
                           retailprice
                    FROM   FN_GetPowerRangePList(@OperatorId, @tempPtypeid) p1
                           LEFT JOIN (SELECT a.ptypeid,
                                             a.attributeid,
                                             b.typeid
                                      FROM   ptypeattribute a
                                             INNER JOIN assistattribute b
                                               ON a.attributeid = b.attributeid
                                      WHERE  typeid = @Assist1TypeID) ls1
                             ON @attrib1 <> -1
                                AND ls1.ptypeid = p1.typeid
                           LEFT JOIN (SELECT a.ptypeid,
                                             a.attributeid,
                                             b.typeid
                                      FROM   ptypeattribute a
                                             INNER JOIN assistattribute b
                                               ON a.attributeid = b.attributeid
                                      WHERE  typeid = @Assist2TypeID) ls2
                             ON @attrib2 <> -1
                                AND ls2.ptypeid = p1.typeid
                           LEFT JOIN (SELECT a.ptypeid,
                                             a.attributeid,
                                             b.typeid
                                      FROM   ptypeattribute a
                                             INNER JOIN assistattribute b
                                               ON a.attributeid = b.attributeid
                                      WHERE  typeid = @Assist3TypeID) ls3
                             ON @attrib3 <> -1
                                AND ls3.ptypeid = p1.typeid
                           LEFT JOIN (SELECT a.ptypeid,
                                             a.attributeid,
                                             b.typeid
                                      FROM   ptypeattribute a
                                             INNER JOIN assistattribute b
                                               ON a.attributeid = b.attributeid
                                      WHERE  typeid = @Assist4TypeID) ls4
                             ON @attrib4 <> -1
                                AND ls4.ptypeid = p1.typeid
                    WHERE  p1.[typeid] <> '00000'
                           AND stop = CASE @ifstop
                                        WHEN '0' THEN '0'
                                        ELSE stop
                                      END
                           AND (parid LIKE @szPtypeId + '%'
                                 OR p1.typeid = @szPtypeid)
                           AND isnull(ls1.attributeid, -1) = CASE
                                                               WHEN @attrib1 = -1 THEN isnull(ls1.attributeid, -1)
                                                               ELSE @attrib1
                                                             END
                           AND isnull(ls2.attributeid, -1) = CASE
                                                               WHEN @attrib2 = -1 THEN isnull(ls2.attributeid, -1)
                                                               ELSE @attrib2
                                                             END
                           AND isnull(ls3.attributeid, -1) = CASE
                                                               WHEN @attrib3 = -1 THEN isnull(ls3.attributeid, -1)
                                                               ELSE @attrib3
                                                             END
                           AND isnull(ls4.attributeid, -1) = CASE
                                                               WHEN @attrib4 = -1 THEN isnull(ls4.attributeid, -1)
                                                               ELSE @attrib4
                                                             END) p1
                   LEFT JOIN Ptypecolor b
                     ON p1.typeid = b.ptypeid
                   LEFT JOIN Ptypesize c
                     ON p1.typeid = c.Ptypeid) p,
           (SELECT ptypeid,
                   sum(isnull(-qty, 0))         AS qty,
                   sum(isnull(-S_Tax_total, 0)) AS S_Tax_total,
                   sum(isnull(tqty, 0))         AS tqty,
                   sum(isnull(T_Tax_total, 0))  AS T_Tax_total,
                   sum(isnull(-salemoney, 0))   AS salemoney,
                   sum(isnull(-taxtotal, 0))    AS taxtotal,
                   sum(isnull(-Tax_total, 0))   AS Tax_total,
                   colorid,
                   sizeid
            FROM   (SELECT Ptypeid,
                           sum(isnull([qty], 0))       AS [Qty],
                           sum(isnull([Tax_total], 0)) AS S_Tax_total,
                           0                           AS [TQty],
                           0                           AS T_Tax_total,
                           sum(isnull([salemoney], 0)) AS SaleMoney,
                           sum(isnull([taxtotal], 0))  AS Taxtotal,
                           sum(isnull([tax_total], 0)) AS Tax_total,
                           colorid,
                           sizeid
                    FROM   #tmp_data
                    WHERE  qty < 0
                    GROUP  BY ptypeid,
                              vchtype,
                              colorid,
                              sizeid
                    UNION ALL
                    SELECT Ptypeid,
                           0                           AS [Qty],
                           0                           AS S_Tax_total,
                           sum(isnull([qty], 0))       AS [TQty],
                           sum(isnull([Tax_total], 0)) AS T_Tax_total,
                           sum(isnull([salemoney], 0)) AS SaleMoney,
                           sum(isnull([taxtotal], 0))  AS Taxtotal,
                           sum(isnull([tax_total], 0)) AS Tax_total,
                           colorid,
                           sizeid
                    FROM   #tmp_data
                    WHERE  qty > 0
                    GROUP  BY ptypeid,
                              vchtype,
                              colorid,
                              sizeid) C
            GROUP  BY ptypeid,
                      colorid,
                      sizeid) Salebill
    WHERE  p.[typeid] = Salebill.ptypeid
           AND p.sizeid = salebill.sizeid
           AND p.colorid = salebill.colorid

    SELECT p.[typeid]                                                     AS ptypeid,
           sum(qty)                                                       AS qty,
           sum(S_Tax_total)                                               AS S_Tax_total,
           sum(Tqty)                                                      AS Tqty,
           sum(T_Tax_total)                                               AS T_Tax_total,
           sum(qty) - sum(Tqty)                                           AS Sqty,
           sum(S_Tax_total) - sum(T_Tax_total)                            AS SX_Tax_total,
           sum(Tax_total)                                                 AS tax_total,
           sum(taxtotal)                                                  AS taxtotal,
           sum(SaleMoney) - sum(Tax_total)                                AS DeductTotal,
           
           ROUND(CAST(sum(qty) - sum(Tqty) AS numeric(24,10)) * CAST(RetailPrice AS numeric(24,10)),@dig_total) AS RetailTotal,
           RIGHT('00000' + CAST(colorid AS VARCHAR), 5)                   AS pctypeid,
           RIGHT('00000' + CAST(sizeid AS VARCHAR), 5)                    AS pstypeid
    FROM   #table_P p
    GROUP  BY p.[typeid],
              p.sizeid,
              p.colorid,
              retailprice
    HAVING abs(sum(qty)) + abs(sum(Tqty)) <> 0
    ORDER  BY p.[typeid],
              p.colorid,
              p.sizeid

GO

IF object_id('tempdb..#table_P') IS NOT NULL
  DROP TABLE #table_P

IF object_id('tempdb..#tmp_data') IS NOT NULL
  DROP TABLE #tmp_data

SET QUOTED_IDENTIFIER OFF

GO

SET ANSI_NULLS ON

GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


Create PROCEDURE  FZQueryRetailSaleList_BS  
(     
      @szPtypeId  	varchar(50),  
      @szKtypeid        varchar(2000),  
      @szBtypeid        varchar(50),  
      @szBeginData 	varchar(50),  
      @szEndData 	varchar(50),  
      @ifstop           varchar(2),  
      @attrib1  	int =-1,  
      @attrib2  	int =-1,  
      @attrib3          int =-1,  
      @attrib4          int =-1 ,  
      @Assist1TypeID    int =-1,  
      @Assist2TypeID    int =-1,  
      @Assist3TypeID    int =-1,  
      @Assist4TypeID    int =-1,  
      @SaleTraitName    varchar(1000),  
      @branchid         varchar(2000),
      @OperatorId       varchar(50)='',
      @ifxiaopiao       VARCHAR(2),     --是否包含未过账小票（1：是，0：否）
      @ifdraft          VARCHAR(2)      --是否包含零售单草稿（1：是，0：否）
 )  
 AS  

--设置变量用于操作员拥有所有多级权限时，优化查询
DECLARE @PowerRangeP BIT --商品
DECLARE @PowerRangeE BIT --职员
DECLARE @PowerRangeA BIT --科目
DECLARE @PowerRangeB BIT --客户
DECLARE @PowerRangeC BIT --机构
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 0 AND TypeID = '00000') SET @PowerRangeP = 1 ELSE SET @PowerRangeP = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 1 AND TypeID = '00000') SET @PowerRangeE = 1 ELSE SET @PowerRangeE = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 3 AND TypeID = '00000') SET @PowerRangeA = 1 ELSE SET @PowerRangeA = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 4 AND TypeID = '00000') SET @PowerRangeB = 1 ELSE SET @PowerRangeB = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 5 AND TypeID = '00000') SET @PowerRangeC = 1 ELSE SET @PowerRangeC = 0



IF OBJECT_ID('tempdb..#FilterB','U') IS NOT NULL   
DROP TABLE #FilterB  
IF OBJECT_ID('tempdb..#FilterE','U') IS NOT NULL   
DROP TABLE #FilterE  
--IF OBJECT_ID('tempdb..#FilterP','U') IS NOT NULL   
--DROP TABLE #FilterP  
IF OBJECT_ID('tempdb..#FilterK','U') IS NOT NULL   
DROP TABLE #FilterK  
CREATE TABLE #FilterB (TypeId VARCHAR(50))    
CREATE TABLE #FilterE (TypeId VARCHAR(50))    
--CREATE TABLE #FilterP (TypeId VARCHAR(50),PORDER INT)    
CREATE TABLE #FilterK (KtypeId VARCHAR(50))      
INSERT  #FilterB(TypeId) SELECT  TypeId FROM  FN_GetPowerRangeBList(@OperatorId, @szBtypeid, '2,3,4,6')     
INSERT  #FilterE(TypeId) SELECT  TypeId FROM  FN_GetPowerRangeEList(@OperatorId, '') 
INSERT  #FilterK(KtypeId) SELECT  KtypeId FROM  FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) 


if object_id('tempdb..#table_S') is not null drop table #table_S  
if object_id('tempdb..#table_P') is not null drop table #table_P  

Declare @tempPtypeID Varchar(50)
SET @tempPtypeID=@szPtypeId

if @branchid is null 
   set  @branchid=''   

if @szPtypeId is null or  @szPtypeId=''
   set  @szPtypeId='%'  

IF OBJECT_ID('tempdb..#temp_data') IS NOT NULL 
   DROP TABLE #temp_data 
CREATE TABLE #temp_data   --创建临时表
(
ptypeid VARCHAR(50),
Qty  numeric(24,10),
S_Tax_total  numeric(24,10),
TQty  numeric(24,10),
T_Tax_total  numeric(24,10),
Taxtotal  numeric(24,10),
SaleMoney  numeric(24,10),
tax_total  numeric(24,10),
vchtype int

)

DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
--select @dig_qty  ,@dig_price ,@dig_total  ,@dig_dis  ,@dig_tax  ,@dig_rate 

if @SaleTraitName='全部' 
   set @SaleTraitName=''   


	INSERT INTO #temp_data 
	SELECT   s.ptypeid,    --统计过账零售单
				  ds.[qty]      	AS Qty, 	
				  ds.[tax_total]  	AS S_Tax_total,  
				  ds.[qty]		AS TQty,   		
				  ds.[tax_total]	AS T_Tax_total, 	
				  ds.[taxtotal] 	AS Taxtotal,			
				  ds.[salemoney]   	AS SaleMoney,
				  ds.[tax_total]   	AS tax_total,
				  s.Vchtype  	
	from Dlydata s,dlydatadetail ds 
	where S.[date] between @szBeginData and @szEndData 
	and  s.vchtype in(12,100) 
	and s.redold='F'
	AND s.dlyorder = ds.dlyorder
	and ((1=@PowerRangeB AND s.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where s.BtypeId = FilterB.TypeId))  
    and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where s.EtypeId = FilterE.TypeId))  
    and exists(select 1  from #FilterK FilterK where s.ktypeId = Filterk.KtypeId)
	and (CustValue1 like '%'+@SaleTraitName+'%'  
			or CustValue2 like '%'+@SaleTraitName+'%'  
			or CustValue3 like '%'+@SaleTraitName+'%'  
			or CustValue4 like '%'+@SaleTraitName+'%'  
			or CustValue5 like '%'+@SaleTraitName+'%'  
			or CustValue6 like '%'+@SaleTraitName+'%'  )	


IF  @ifdraft=1  --统计包含零售单草稿
BEGIN 
INSERT INTO #temp_data
            Select	b.Ptypeid,
			-bd.[qty]      		AS Qty, 	
			-bd.[tax_total]  	As S_Tax_total,  
			-bd.[qty]		    AS TQty,   		
			-bd.[tax_total]		AS T_Tax_total, 	
			-bd.[taxtotal] 		AS Taxtotal,			
			-bd.[salemoney]   	AS SaleMoney,
			-bd.[tax_total]   	AS tax_total,
            b.vchtype
    FROM    Bakdly b, BakDlyDetail bd
    WHERE   b.[date] BETWEEN @szBeginData AND @szEndData
	    AND b.vchtype IN ( 12, 100)
	    AND b.Ptypeid<>''
            AND b.dlyorder = bd.dlyorder           
            and ((1=@PowerRangeB AND b.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where b.BtypeId = FilterB.TypeId))  
            and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where b.EtypeId = FilterE.TypeId))  
            and exists(select 1  from #FilterK FilterK where b.ktypeId = Filterk.KtypeId)
            AND ( CustValue1 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue2 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue3 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue4 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue5 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue6 LIKE '%' + @SaleTraitName + '%'
                )
END

IF  @ifxiaopiao=1 AND @SaleTraitName = '' --统计包含未过账小票
BEGIN

INSERT INTO #temp_data
            Select	
             PSL.Ptypeid,
			-SUM(PSL.[qty])  AS Qty, 	
			-SUM(PSL.[total])  As S_Tax_total,  
			-SUM(PSL.[qty])	AS TQty,   		
			-SUM(PSL.[total])	AS T_Tax_total, 	
			        0   AS  Taxtotal,			
			-SUM(PSL.[total])  AS SaleMoney,
			-SUM(PSL.[total])  AS tax_total,
            vchtype=12 --POS过账后默认为零售单
           
    FROM    dbo.tpx_SaleList PSL,dbo.tpx_SaleIndex PSI
    WHERE   PSI.[Saledate] BETWEEN @szBeginData AND @szEndData
	        AND PSL.Ptypeid<>''
            AND PSL.ZBKeyId=PSI.keyId 
            and ((1=@PowerRangeB AND PSI.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where PSI.BtypeId = FilterB.TypeId))  
            and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where PSI.Salesman = FilterE.TypeId))  
            and exists(select 1  from #FilterK FilterK where PSI.ktypeId = Filterk.KtypeId)
            AND PSI.Draft=0 --Draft 结存标志[0-POS小票,1-草稿] 
            GROUP BY PSL.Ptypeid
            
            /*
            AND ( CustValue1 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue2 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue3 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue4 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue5 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue6 LIKE '%' + @SaleTraitName + '%'
             ) */--POS小票那无自定义类型
END

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

	Select  p1.[typeid],RetailPrice,porder    
		  INTO #tmp_ptype
          From FN_GetPowerRangePList(@OperatorId,@tempPtypeID) p1
  	      left join ( select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b   
   			 where a.attributeid = b.attributeid and typeid = @Assist1TypeID ) ls1  on  @attrib1 <> -1 and ls1.ptypeid = p1.typeid  
		  left join ( select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b   
             where a.attributeid = b.attributeid and typeid = @Assist2TypeID ) ls2  on  @attrib2 <> -1 and ls2.ptypeid = p1.typeid  
          left join ( select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b  
             where a.attributeid = b.attributeid and typeid = @Assist3TypeID ) ls3  on  @attrib3 <> -1 and ls3.ptypeid = p1.typeid  
		  left join ( select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b  
			 where a.attributeid = b.attributeid and typeid = @Assist4TypeID ) ls4  on  @attrib4 <> -1 and ls4.ptypeid = p1.typeid  
     Where stop =case @ifstop when '0' then '0' else stop end and p1.typeid<>'00000'  
	 and (parid like @szPtypeId+'%' or p1.typeid =@szPtypeid )    
	 and isnull(ls1.attributeid,-1) =  case when @attrib1 = -1 then isnull(ls1.attributeid,-1) else @attrib1 end  
     and isnull(ls2.attributeid,-1) =  case when @attrib2 = -1 then isnull(ls2.attributeid,-1) else @attrib2 end  
     and isnull(ls3.attributeid,-1) =  case when @attrib3 = -1 then isnull(ls3.attributeid,-1) else @attrib3 end  
     and isnull(ls4.attributeid,-1) =  case when @attrib4 = -1 then isnull(ls4.attributeid,-1) else @attrib4 end  


------------------------------------------------------------------
select	p.[typeid]							as ptypeid,
		porder,  
        sum(qty) 							as qty,
		sum(Tqty)							as Tqty,
        sum(qty) -sum(Tqty)					as Sqty,  
        sum(S_Tax_total)					as S_Tax_total,  
		sum(T_Tax_total)					as T_Tax_total,
		sum(S_Tax_total)-sum(T_Tax_total)	as SX_Tax_total, 	
		sum(taxtotal)						as taxtotal, 
		ROUND(CAST((SUM(qty) - SUM(Tqty)) AS NUMERIC(24,10))*CAST(RetailPrice AS NUMERIC(24,10)),@dig_total) RetailTotal,
		sum(SaleMoney)						as SaleMoney,
		sum(tax_total)						as tax_total,
        sum(SaleMoney)-sum(tax_total)		as DeductTotal
From
(  	Select   p.[typeid],   
	         isnull([Qty],0)		AS [Qty],
			 isnull(S_Tax_total,0)	as [S_Tax_total],
			 isnull(Tqty,0)			AS Tqty,
			 isnull(T_Tax_total,0)  as [T_Tax_total],	
			 isnull([SaleMoney], 0) AS [SaleMoney],		 
	         isnull([taxtotal], 0)  as Taxtotal,
	         isnull([tax_total], 0) as Tax_total,  	    
	         p.porder,
	         p.RetailPrice  	
	  From 
		      #tmp_ptype p 
		  LEFT join 
			(		SELECT	ptypeid,
       						sum(isnull(-qty,0)) 	        AS qty,
       						sum(isnull(-S_Tax_total,0))     AS S_Tax_total,
       						sum(isnull(tqty,0))				AS tqty,  		
       						sum(isnull(T_Tax_total,0))      AS T_Tax_total,
       						sum(isnull(-taxtotal,0))        AS taxtotal,		
       						sum(isnull(-salemoney,0))       AS SaleMoney,
       						sum(isnull(-tax_total,0))       AS tax_total		
	   				from
					(  	
						Select		  ptypeid,
									  sum(isnull([qty], 0))          	AS Qty, 		--销售数量
									  sum(isnull([tax_total],0))     	As S_Tax_total,  	--价税合计（销售）
									  0          						AS TQty,   		--退货数量
									  0          					  	AS T_Tax_total, 	--价税合计（退货）
									  sum(isnull([taxtotal],0))      	AS Taxtotal,		--税额			
									  sum(isnull([salemoney],0))     	AS SaleMoney,
									  sum(isnull([tax_total],0))     	AS tax_total  	
						FROM #temp_data
						WHERE Qty < 0
						GROUP BY  ptypeid,vchtype  		
						UNION ALL
						Select		  Ptypeid,  
									  0									AS Qty, 		--销售数量
									  0									AS S_Tax_total,  	--价税合计（销售）
									  sum(isnull([qty], 0))			    AS TQty,   		--退货数量
									  sum(isnull([tax_total],0))		AS T_Tax_total, 	--价税合计（退货）
									  sum(isnull([taxtotal],0))      	AS Taxtotal,		--税额				  
									  sum(isnull([salemoney],0))     	AS SaleMoney,
									  sum(isnull([tax_total],0))     	AS tax_total			
						FROM #temp_data
						WHERE Qty > 0          		      	     		      			      
    					GROUP BY  ptypeid,vchtype  
					) C  
	   			group by ptypeid    
         ) Salebill  on p.[typeid]=Salebill.ptypeid  
)p  
group by [typeid],p.porder,RetailPrice  
order by p.porder,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].[FZQueryRetailSale_BS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FZQueryRetailSale_BS]
GO




CREATE PROCEDURE FZQueryRetailSale_BS
    (
      @szPtypeId VARCHAR(50),
      @szKtypeid VARCHAR(2000),
      @szBtypeid VARCHAR(50),
      @szBeginData VARCHAR(50),
      @szEndData VARCHAR(50),
      @ifstop VARCHAR(2),
      @SaleTraitName VARCHAR(1000),
      @branchid VARCHAR(2000),
      @OperatorId VARCHAR(50) = '',
      @ifxiaopiao VARCHAR(2),  --是否包含未过账小票（1：是，0：否）
      @ifdraft VARCHAR(2)      --是否包含零售单草稿（1：是，0：否）
    )
AS 

--设置变量用于操作员拥有所有多级权限时，优化查询
DECLARE @PowerRangeP BIT --商品
DECLARE @PowerRangeE BIT --职员
DECLARE @PowerRangeA BIT --科目
DECLARE @PowerRangeB BIT --客户
DECLARE @PowerRangeC BIT --机构
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 0 AND TypeID = '00000') SET @PowerRangeP = 1 ELSE SET @PowerRangeP = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 1 AND TypeID = '00000') SET @PowerRangeE = 1 ELSE SET @PowerRangeE = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 3 AND TypeID = '00000') SET @PowerRangeA = 1 ELSE SET @PowerRangeA = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 4 AND TypeID = '00000') SET @PowerRangeB = 1 ELSE SET @PowerRangeB = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 5 AND TypeID = '00000') SET @PowerRangeC = 1 ELSE SET @PowerRangeC = 0

DECLARE @PStop BIT  
IF @ifstop = '0' SELECT @PStop = 0  
ELSE SELECT @PStop = 1

    DECLARE @szparid VARCHAR(50)  
    SET nocount ON  

    IF @branchid IS NULL 
        SET @branchid = ''  

    IF @szPtypeId IS NULL
        OR @szPtypeId = '' 
        SET @szparid = '00000'  
    ELSE 
        SET @szparid = @szPtypeId  

    IF @szPtypeId IS NULL 
        SET @szPtypeId = '' 

IF OBJECT_ID('tempdb..#FilterB','U') IS NOT NULL   
DROP TABLE #FilterB  
IF OBJECT_ID('tempdb..#FilterE','U') IS NOT NULL   
DROP TABLE #FilterE  
IF OBJECT_ID('tempdb..#FilterP','U') IS NOT NULL   
DROP TABLE #FilterP  
IF OBJECT_ID('tempdb..#FilterK','U') IS NOT NULL   
DROP TABLE #FilterK  
CREATE TABLE #FilterB (TypeId VARCHAR(50))    
CREATE TABLE #FilterE (TypeId VARCHAR(50))    
CREATE TABLE #FilterP (TypeId VARCHAR(50),PORDER INT)
CREATE TABLE #FilterK (KtypeId VARCHAR(50))      
INSERT  #FilterB(TypeId) SELECT  TypeId FROM  FN_GetPowerRangeBList(@OperatorId, @szBtypeid, '2,3,4,6')     
INSERT  #FilterE(TypeId) SELECT  TypeId FROM  FN_GetPowerRangeEList(@OperatorId, '')     
--INSERT  #FilterP(TypeId) SELECT  TypeId FROM  FN_GetPowerRangePList(@OperatorId, @szPtypeId) P WHERE (@PStop = 1 OR Stop = 0)
INSERT  #FilterP(TypeId,PORDER) 
SELECT    [typeid], porder
                          FROM      FN_GetPowerRangePTree(@OperatorId, @szPtypeId)  
                          WHERE     
                          deleted = 0 
                          AND [typeid] <> '00000' 
                          AND (@PStop = 1 OR Stop = 0) 
                          AND ( [parid] = @szparid OR ( typeid = @szPtypeId AND sonnum = 0 )) 
IF OBJECT_ID('tempdb..#tempPList','U') IS NOT NULL   
	DROP TABLE #tempPList  
SELECT TypeID,RetailPrice INTO #tempPList FROM dbo.FN_GetPowerRangePList('00000','00000') WHERE @PStop = 1 OR Stop = 0


INSERT  #FilterK(KtypeId) SELECT  KtypeId FROM  FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) 

    --IF OBJECT_ID('tempdb..#table_P') IS NOT NULL 
    --    DROP TABLE #table_P  

    IF @SaleTraitName = '全部' 
        SET @SaleTraitName = ''   
        
DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
--select @dig_qty  ,@dig_price ,@dig_total  ,@dig_dis  ,@dig_tax  ,@dig_rate 

IF OBJECT_ID('tempdb..#table_S') IS NOT NULL 
   DROP TABLE #table_S 
CREATE TABLE #table_S   --创建临时表
(
ptypeid VARCHAR(50),
Qty  numeric(24,10),
S_Tax_total  numeric(24,10),
TQty  numeric(24,10),
T_Tax_total  numeric(24,10),
Taxtotal  numeric(24,10),
SaleMoney  numeric(24,10),
tax_total  numeric(24,10),
vchtype int
)


INSERT INTO #table_S    --统计过账零售单
    Select	s.ptypeid,
			ds.[qty]      		AS Qty, 	
			ds.[tax_total]  	As S_Tax_total,  
			ds.[qty]		    AS TQty,   		
			ds.[tax_total]		AS T_Tax_total, 	
			ds.[taxtotal] 		AS Taxtotal,			
			ds.[salemoney]   	AS SaleMoney,
			ds.[tax_total]   	AS tax_total,
            s.vchtype
    FROM    DlyData s, dlydatadetail ds
    WHERE   S.[date] BETWEEN @szBeginData AND @szEndData
			AND s.vchtype IN ( 12, 100)
    	    AND s.redold = 'F'  
            AND s.dlyorder = ds.dlyorder           
            and ((1=@PowerRangeB AND s.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where s.BtypeId = FilterB.TypeId))  
            and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where s.EtypeId = FilterE.TypeId))  
            and exists(select 1  from #FilterK FilterK where s.ktypeId = Filterk.KtypeId)  	
            AND ( CustValue1 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue2 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue3 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue4 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue5 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue6 LIKE '%' + @SaleTraitName + '%'
                )

IF  @ifdraft=1  --统计包含零售单草稿	
BEGIN 
INSERT INTO #table_S
            Select	b.Ptypeid,
			-bd.[qty]      		AS Qty, 	
			-bd.[tax_total]  	As S_Tax_total,  
			-bd.[qty]		    AS TQty,   		
			-bd.[tax_total]		AS T_Tax_total, 	
			-bd.[taxtotal] 		AS Taxtotal,			
			-bd.[salemoney]   	AS SaleMoney,
			-bd.[tax_total]   	AS tax_total,
            b.vchtype
    FROM    Bakdly b, BakDlyDetail bd
    WHERE   b.[date] BETWEEN @szBeginData AND @szEndData
	    AND b.vchtype IN ( 12, 100)
	    AND b.Ptypeid<>''
            AND b.dlyorder = bd.dlyorder           
            and ((1=@PowerRangeB AND b.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where b.BtypeId = FilterB.TypeId))  
            and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where b.EtypeId = FilterE.TypeId))  
            and exists(select 1  from #FilterK FilterK where b.ktypeId = Filterk.KtypeId)
            AND ( CustValue1 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue2 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue3 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue4 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue5 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue6 LIKE '%' + @SaleTraitName + '%'
                )
END

IF  @ifxiaopiao=1 AND @SaleTraitName = '' --统计包含未过账小票
BEGIN

INSERT INTO #table_S
            Select	
             PSL.Ptypeid,
			-SUM(PSL.[qty])  AS Qty, 	
			-SUM(PSL.[Total])  As S_Tax_total,  
			-SUM(PSL.[qty])	AS TQty,   		
			-SUM(PSL.[Total])	AS T_Tax_total, 	
			            0    AS Taxtotal,			
			-SUM(PSL.[Total])  AS SaleMoney,
			-SUM(PSL.[Total])  AS tax_total,
            vchtype=12						 --POS过账后默认为零售单
    FROM    dbo.tpx_SaleList PSL,dbo.tpx_SaleIndex PSI
    WHERE   PSI.[Saledate] BETWEEN @szBeginData AND @szEndData
	        AND PSL.Ptypeid<>''
            AND PSL.ZBKeyId=PSI.keyId           
            and ((1=@PowerRangeB AND PSI.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where PSI.BtypeId = FilterB.TypeId))  
            and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where PSI.Salesman = FilterE.TypeId))  
            and exists(select 1  from #FilterK FilterK where PSI.ktypeId = Filterk.KtypeId) 	
            AND PSI.Draft=0 --Draft 结存标志[0-POS小票,1-草稿] 
            GROUP BY PSL.Ptypeid,PSL.[qty],PSL.[Total], PSL.retailprice
END




    SELECT  p.[typeid] AS ptypeid,
            SUM(qty) AS qty,                                          --销售数量
            SUM(Tqty) AS Tqty,                                        --退货数量
            SUM(qty) - SUM(Tqty) AS Sqty,                             --实际销售数量
            SUM(S_Tax_total) AS S_Tax_total,                          --实际销售含税金额
            SUM(T_Tax_total) AS T_Tax_total,                          --退货含税金额
            SUM(S_Tax_total) - SUM(T_Tax_total) AS SX_Tax_total,      --实际销售含税金额
            SUM(taxtotal) AS taxtotal,                                --税额
            SUM(RetailTotal) AS RetailTotal,						  --零售金额
            SUM(SaleMoney) AS SaleMoney,                              --实际销售金额
            SUM(tax_total) AS tax_total,                              --含税金额
            SUM(SaleMoney) - SUM(tax_total) AS DeductTotal            --抽成额          
    FROM    ( SELECT    p.[typeid],
                        p.porder,
                        [Qty],
                        [S_Tax_total],
                        [tqty],
                        [T_Tax_total],
                        [taxtotal],
                        [salemoney],
                        [tax_total],
                        RetailTotal
              FROM      #FilterP p
                        LEFT JOIN ( SELECT  SUBSTRING(ptypeid, 1, LEN(@szptypeid) + 5) AS ptypeid,
                                            -SUM(qty) AS qty,
                                            -SUM(S_Tax_total) AS S_Tax_total,
                                            SUM(tqty) AS tqty,
                                            SUM(T_Tax_total) AS T_Tax_total,
                                            -SUM(taxtotal) AS taxtotal,
                                            -SUM(salemoney) AS SaleMoney,
                                            -SUM(tax_total) AS tax_total,
                                            ROUND(CAST((SUM(-qty) - SUM(tqty)) AS NUMERIC(24,10))*CAST(RetailPrice AS NUMERIC(24,10)),@dig_total) RetailTotal
                                    FROM    (  
											SELECT  Ptypeid,
													SUM(ISNULL(s.[qty], 0)) AS Qty, 				--销售数量
													SUM(ISNULL(s.[tax_total], 0)) AS S_Tax_total,  	--价税合计（销售）
													0 AS TQty,   									--退货数量
													0 AS T_Tax_total, 								--价税合计（退货）
													SUM(ISNULL(s.[taxtotal], 0)) AS Taxtotal,		--税额
													SUM(ISNULL(s.[salemoney], 0)) AS SaleMoney,
													SUM(ISNULL(s.[tax_total], 0)) AS tax_total
											FROM     #table_S S
											WHERE    qty < 0
											GROUP BY ptypeid, vchtype
											
											UNION ALL
											
											SELECT  Ptypeid,
													0 AS Qty, 										--销售数量
													0 AS S_Tax_total,  								--价税合计（销售）
													SUM(ISNULL(s.[qty], 0)) AS TQty,   				--退货数量
													SUM(ISNULL(s.[tax_total], 0)) AS T_Tax_total, 	--价税合计（退货）
													SUM(ISNULL(s.[taxtotal], 0)) AS Taxtotal,		--税额
													SUM(ISNULL(s.[salemoney], 0)) AS SaleMoney,
													SUM(ISNULL(s.[tax_total], 0)) AS tax_total
											FROM      #table_S S
											WHERE     qty > 0
											GROUP BY  ptypeid, vchtype
											) C
											INNER JOIN #tempPList D ON D.typeid = C.ptypeid
									 GROUP BY SUBSTRING(ptypeid, 1, LEN(@szptypeid) + 5),RetailPrice
                           ) Salebill ON p.[typeid] = Salebill.ptypeid
	            ) P
	    GROUP BY p.porder,[typeid]
    ORDER BY p.porder,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].[FZSaleBillDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FZSaleBillDetail]
GO

/*    
  作者:QF    
  时间:2011-08-18       
  主要内容:功能增加 发货类型、退货类型    
*/    
-------------------------销售单据统计----------------------------    
CREATE PROCEDURE  FZSaleBillDetail       
(    
 @IsBillMode  int = 0, --０：要显示商品、１：单据模式不显示商品    
 @VchTypeID   varchar(100),    
 @PtypeID   varchar(50),    
 @BtypeID   varchar(50),    
 @KtypeID   varchar(2000),    
 @BeginDate     varchar(12),    
 @EndDate       varchar(12),    
 @branchid   varchar(2000)='',    
 @Operatorid  varchar(50) ,    
 @OpID  INT = 0   --0-全部 , 其他为具体类型     
)     
AS    
--cs补齐所有单据 by dmj 2011.8.24    
--总部和加盟商共用一个，当不进行筛选单据的情况下，要把单据范围补齐    
-- IF LEFT(@branchid,5)='00001'    
-- BEGIN    
--  IF @VchTypeID is null or @VchTypeID=''    
--      SET @VchTypeID='100,11,45,24,12,222,224' --总部统计的销售主体单据    
-- END    
-- ELSE    
-- BEGIN    
--  IF @VchTypeID is null or @VchTypeID=''    
--      SET @VchTypeID='11,12,45,24'   --加盟商统计的销售主体单据    
-- END    
IF @VchTypeID is null or @VchTypeID=''    
 SET @VchTypeID='100,11,45,24,12,222,224,11,12,45,24'    
Declare @OperatorIsJM bit    
select @OperatorIsJM = SelfHelp from Branch a Left join Employee b on a.branchid = b.branchid where b.typeid = @OperatorId    
if object_id('tempdb..#FilterEtype') is not null drop table #FilterEtype     
if object_id('tempdb..#FilterPtype') is not null drop table #FilterPtype     
if object_id('tempdb..#FilterBtype') is not null drop table #FilterBtype    
if object_id('tempdb..#FilterKtype') is not null drop table #FilterKtype    
if object_id('tempdb..#FilterVtype') is not null drop table #FilterVtype    
Select distinct TypeId into #FilterEtype from FN_GetPowerRangeEList(@OperatorId,'')    
Select distinct TypeId into #FilterPtype from FN_GetPowerRangePList(@OperatorId,@PtypeID)               
Select distinct TypeId into #FilterBtype from FN_GetPowerRangeBList(@OperatorId,@BtypeID,'2,3,4,6')    
Select distinct KtypeId into #FilterKtype from FN_GetStockListOfBranch(@OperatorID,@BranchId,@Ktypeid) where SelfHelp = @OperatorIsJM    
select distinct GetID into #FilterVtype FROM FN_GetIdStrListTable(@VchTypeID)     
              ---------------------为了显示单据的编号、仓库等关联其它表-----------------------------/                
if @IsBillMode = 0    
begin    
 Select  ds.DlyOrder,ds.[date],ds.ptypeID,ds.btypeID,dn.[number],    
  --case when dn.ktypeid ='9999900002' then '8888800002' else dn.ktypeid end as Ktypeid,    
  dn.ktypeid,dn.[Date] AS dlydate,dn.Summary,    
  ds.VchCode,ds.VchType,-ds.qty as qty,       
  (-ds.total -case when ds.vchtype in (100,101) then -SaleMoney else -bargaintotal end) as [convert],    
  ( -bargaintotal) as bargaintotal ,(-bargaintotal)-(-CostTotal) as Profittotal,-costTotal as CostTotal,    
  -ds.Total as Total,    
   Cast (cast((case when ( ds.Total)=0.00 then 0.00 else    
          (-ds.total -  case when ds.vchtype in (100,101) then -SaleMoney else -bargaintotal end )/( -ds.Total)  end *100) as numeric(24,2)) as varchar(30)) as RLrate,  
   ds.Comment    
 from    dlydata  ds     
  left join dlyndx dn on ds.vchcode=dn.vchcode    
  inner join #FilterEtype FilterE  on ds.EtypeId = FilterE.TypeId    
  inner join #FilterPtype FilterP  on ds.PtypeId = FilterP.TypeId    
  inner join #FilterBtype FilterB  on ds.BtypeId = FilterB.TypeId    
  inner join #FilterKtype FilterK on ds.ktypeId = Filterk.KtypeId    
  inner join #FilterVtype FilterVch on ds.VchType=FilterVch.GetID    
 where      
         ds.BillType=2 and  ds.redold='F'                    
         and  ds.Date between @BeginDate and @EndDate    
         --and usedtype =case when ds.vchtype in(222,224) then 1 else usedtype end     
  and ((ds.vchtype not in(222,224)) or (usedtype = 1))    
         --AND ds.OpId = (CASE WHEN @OpID=0 THEN ds.OpId ELSE @OpID END )    
  and ((@OpID=0) or (ds.OpId = @OpID))    
        /*     
        and ds.Vchtype = case  @VchtypeID when 0 then ds.Vchtype else @VchtypeID    end    
        and ds.PtypeID like @PtypeID+'%'    
        and ds.BtypeID like @BtypeID+'%'                            
        and ds.KtypeID like @KtypeID+'%'    
        and ds.branchid like @branchid+'%'     
        */     
        --and exists(select 1  from #FilterEtype FilterE  where ds.EtypeId = FilterE.TypeId)   --ljh 2011-1-19            
        --and exists(select 1  from #FilterPtype FilterP  where ds.PtypeId = FilterP.TypeId)      
        --and exists(select 1  from #FilterBtype FilterB  where ds.BtypeId = FilterB.TypeId)              
        --and exists(select 1  from #FilterKtype FilterK where ds.ktypeId = Filterk.KtypeId)         
        --and exists(select GetID FROM #FilterVtype FilterVch WHERE ds.VchType=FilterVch.GetID)  --单据类型  
 order by  dn.[number],ds.[date],ds.ptypeID  
end    
else    
begin    
 Select  ds.VchCode, ds.[date],ds.VchType,dn.[number],    
  --case when dn.ktypeid ='9999900002' then '8888800002' else dn.ktypeid end as Ktypeid,    
  dn.ktypeid,ds.btypeid,dn.[Date] AS dlydate,dn.Summary,    
         sum(-ds.qty) as Qty ,sum(-ds.total - case when ds.vchtype in (100,101) then -SaleMoney else -bargaintotal end ) as [convert],    
  sum(-ds.bargaintotal) as bargaintotal,     
  sum(-ds.costTotal) costTotal,    
  sum((-bargaintotal)-(-CostTotal)) as Profittotal,    
         Cast (cast((case when sum( ds.Total)=0.00 then 0.00 else    
         sum(-ds.total - case when ds.vchtype in (100,101) then -SaleMoney else -bargaintotal end)/sum( -ds.Total)  end *100) as numeric(24,2)) as varchar(30)) as RLrate                 
 from dlydata  ds     
 left join dlyndx dn on ds.vchcode=dn.vchcode    
  inner join #FilterEtype FilterE  on ds.EtypeId = FilterE.TypeId    
  inner join #FilterPtype FilterP  on ds.PtypeId = FilterP.TypeId    
  inner join #FilterBtype FilterB  on ds.BtypeId = FilterB.TypeId    
  inner join #FilterKtype FilterK on ds.ktypeId = Filterk.KtypeId    
  inner join #FilterVtype FilterVch on ds.VchType=FilterVch.GetID    
 where  ds.BillType=2 and  ds.redold='F'                    
        and  ds.Date between @BeginDate and @EndDate    
        --and usedtype =case when ds.vchtype in(222,224) then 1 else usedtype end    
         --AND ds.OpId = (CASE WHEN @OpID=0 THEN ds.OpId ELSE @OpID END )    
        and ((ds.vchtype not in(222,224)) or (usedtype = 1))    
         --AND ds.OpId = (CASE WHEN @OpID=0 THEN ds.OpId ELSE @OpID END )    
        and ((@OpID=0) or (ds.OpId = @OpID))    
        /*    
        and ds.Vchtype = case  @VchtypeID when 0 then ds.Vchtype else @VchtypeID    end    
        and ds.PtypeID like @PtypeID+'%'    
        and ds.BtypeID like @BtypeID+'%'                            
        and ds.KtypeID like @KtypeID+'%'     
        and ds.branchid like @branchid+'%'    
  */    
        --and exists(select 1  from #FilterEtype FilterE  where ds.EtypeId = FilterE.TypeId)   --ljh 2011-1-19                         
        --and exists(select 1  from #FilterPtype FilterP  where ds.PtypeId = FilterP.TypeId)      
        --and exists(select 1  from #FilterBtype FilterB  where ds.BtypeId = FilterB.TypeId)              
        --and exists(select 1  from #FilterKtype FilterK where ds.ktypeId = Filterk.KtypeId)         
        --and exists(select GetID FROM #FilterVtype FilterVch WHERE ds.VchType=FilterVch.GetID)  --单据类型     
  Group by ds.Vchcode,ds.[date],dn.[number],ds.VchType,dn.kTypeID,ds.btypeid,dn.Date,dn.Summary
  order by  dn.[number],ds.[date],ds.Vchcode     
end    
      
if object_id('tempdb..#FilterEtype') is not null drop table #FilterEtype     
if object_id('tempdb..#FilterPtype') is not null drop table #FilterPtype     
if object_id('tempdb..#FilterBtype') is not null drop table #FilterBtype    
if object_id('tempdb..#FilterKtype') is not null drop table #FilterKtype    
if object_id('tempdb..#FilterVtype') is not null drop table #FilterVtype    


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


/*
  作者:QF
  时间:2011-08-18			
  主要内容:功能增加 发货类型、退货类型
*/
-------------------------销售单据尺码、颜色明细统计----------------------------
CREATE PROCEDURE  FZSaleBillDetailCs   
(
  @VchTypeID  	varchar(100),
  @PtypeID  	varchar(50),
  @BtypeID  	varchar(50),
  @KtypeID  	varchar(2000),
  @BeginDate    varchar(12),
  @EndDate      varchar(12),
  @sizeID  	int = -1 ,
  @ColorID 	int = -1,
  @branchid 	varchar(2000)='',
  @OperatorId   varchar(50),
	@OpID		INT = 0   --0-全部 , 其他为具体类型  
)
AS
--cs补齐所有单据 by dmj 2011.8.24
--总部和加盟商共用一个，当不进行筛选单据的情况下，要把单据范围补齐
-- IF LEFT(@branchid,5)='00001'
-- BEGIN
-- 	IF @VchTypeID is null or @VchTypeID=''
-- 	    SET @VchTypeID='100,11,45,24,12,222,224'	--总部统计的销售主体单据
-- END
-- ELSE
-- BEGIN
-- 	IF @VchTypeID is null or @VchTypeID=''
-- 	    SET @VchTypeID='11,12,45,24'			--加盟商统计的销售主体单据
-- END
IF @VchTypeID is null or @VchTypeID=''
	SET @VchTypeID='100,11,45,24,12,222,224,11,12,45,24'
Declare @OperatorIsJM bit
select @OperatorIsJM = SelfHelp from Branch a Left join Employee b on a.branchid = b.branchid where b.typeid = @OperatorId
-------------明细格式-------------------
Select  ds.DlyOrder,ds.Vchcode,ds.Vchtype, ds.[date],ds.PtypeID,ds.BtypeID,
	--case when dn.ktypeid ='9999900002' then '8888800002' else dn.ktypeid end as Ktypeid,
	dn.ktypeid,dn.[Date] AS dlydate,dn.Summary,
	right('00000'+CAST(dsd.colorid as VARCHAR),5) as pctypeid,
	right('00000'+CAST(dsd.sizeid as VARCHAR),5) as pstypeid,
	-dsd.Qty  as Qty , 
	(-dsd.bargaintotal) as bargaintotal,
	(-dsd.total-  (case when ds.vchtype in (100,101) then -dsd.SaleMoney else -dsd.bargaintotal end) ) as [Convert] ,number                      
from dlydata  ds    
	inner join dlyndx dn on ds.vchcode = dn.vchcode
	inner join dlydataDetail  dsd  on  dsd.DlyOrder  =  ds.DlyOrder
where  ds.billtype=2  
and  ds.usedtype =case when ds.vchtype in(222,224) then 1 else ds.usedtype end
and  dn.RedOld = 'F' 
and  ds.Date >=  @BeginDate  and  ds.date  <=   @EndDate
and  dsd.SizeID = case @SizeID when -1 then  dsd.SizeID  else @SizeID  end
and  dsd.ColorID = case @ColorID when -1 then  dsd.ColorID  else @ColorID  end 
AND ds.OpId = (CASE WHEN @OpID=0 THEN ds.OpId ELSE @OpID END )
/*
and  ds.Vchtype = case  @VchtypeID when 0 then ds.Vchtype else @VchtypeID    end
and  left(ds.PtypeID,len(@PtypeID)) = @PtypeID
and  left(ds.BtypeID,len(@BtypeID)) = @BtypeID                        
and  left(ds.KtypeID,len(@KtypeID)) = @KtypeID  
and ds.branchid like @branchid+'%'
*/
and exists(select 1  from FN_GetPowerRangeEList(@OperatorId,'') FilterE  where ds.EtypeId = FilterE.TypeId)		 --ljh 2011-1-19              	  			
and exists(select 1  from FN_GetPowerRangePList(@OperatorId,@PtypeID) FilterP  where ds.PtypeId = FilterP.TypeId)  
and exists(select 1  from FN_GetPowerRangeBList(@OperatorId,@BtypeID,'2,3,4,6') FilterB  where ds.BtypeId = FilterB.TypeId)  	       
and exists(select 1  from FN_GetStockListOfBranch(@OperatorID,@BranchId,@Ktypeid) FilterK where ds.ktypeId = Filterk.KtypeId and selfhelp = @OperatorIsJM)     
and exists(select GetID FROM FN_GetIdStrListTable(@VchTypeID) FilterVch WHERE ds.VchType=FilterVch.GetID)  --单据类型	
order by ds.[date],ds.PtypeID            


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

--------------------------2011-08-18修改，仓库分支中增加一个返回的BCTYPEID，BUG号502------------------
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FzGetGroupList]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FzGetGroupList]
GO

--  ********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：F_B_GetGroupList                                                   
--  ||   过程功能：得到基本信息的类别树  
--  ||=========================================================================================  
--  ||   参数说明：  参数名称         类型            意义                     输入输出  
--  ||            -----------------------------------------------------------------------------  
--  ||            @cMode  char(5)  :基本信息类型参数   IN  
--  ||            @szTypeid  varchar(50) :根节点Typeid   IN  
--  ||=========================================================================================  

/*
作者：cqhua
日期：2011-08-18
修改原因：默认仓库字段参数改了 defaultstock==>IsDefault
2011-08-29 会计科目加权限
*/
   
CREATE PROCEDURE FzGetGroupList
    (
      @OperatorID VARCHAR(50),
      @cMode VARCHAR(5),
      @szTypeid VARCHAR(50),
      @szFullName VARCHAR(66) = '',
      @szUserCode VARCHAR(26) = '',
      @szStopDate VARCHAR(10) = '',
      @szBarCode VARCHAR(50) = '',  --特殊说明下，职员选择时@szBarCode代表的职员所属的机构Id，不要了
      @szName VARCHAR(66) = '',
      @szIssueDate VARCHAR(10) = '',
      @SearchFlag BIT,
      @BranchId VARCHAR(50) = '00001',
      @FZCSCASHBANK CHAR(1) = ''
    )
AS 
/*
alter by hww 2011年10月12日15:49:08 增加参数@FZCSCASHBANK，区别是否是CS中的现金银行 1 := 是
*/
    SET nocount ON  
    DECLARE @con INT  
    SELECT  @con = stats
    FROM    syscon
    WHERE   [order] = 36  
    DECLARE @TableName VARCHAR(100)
    SET @TableName = 'Btype '   
--alter by hww 2011年9月29日16:26:00 CS在会计科目上是没有权限，已总部机构为准
if @cMode = 'A' and exists(select * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZCS')
BEGIN
	SELECT @OperatorID = '00000',@BranchId = '0000100001'
	--特殊处理现金科目和银行帐户同时显示
	IF @FZCSCASHBANK = '1' 
	BEGIN
		IF @SearchFlag = 1 --list
		BEGIN
		    SELECT  	Typeid AS Atypeid,
                    		TYPEID,
                    		PARID,
                    		SONNUM,
                    		USERCODE,
                    		FULLNAME,
                    		[NAME],
                    		NAMEPY,
                    		COMMENT,
                    		CASE WHEN @BranchId = '0000100001' THEN '00001'
                         	ELSE branchid
                    		END AS branchid,
                    		rec,
                    		0 AS paridstop
            			FROM    atype p
            		WHERE   sonnum = 0	
            		AND     branchid = @BranchId
            		AND     (TypeID LIKE '0000100003%' OR TypeID LIKE '0000100004%')
            		AND 	p.fullname LIKE '%' + @szFullName + '%'
                        AND 	usercode LIKE '%' + @szUserCode + '%'
			and     deleted = 0
		END
		ELSE --tree
		BEGIN
		    SELECT  	Typeid AS Atypeid,
                    		TYPEID,
                    		PARID,
                    		SONNUM,
                    		USERCODE,
                    		FULLNAME,
                    		[NAME],
                    		NAMEPY,
                    		COMMENT,
                    		CASE WHEN @BranchId = '0000100001' THEN '00001'
                         	ELSE branchid
                    		END AS branchid,
                    		rec,
                    		0 AS paridstop
            			FROM    atype p
            		WHERE   branchid = @BranchId
			AND     (TypeID LIKE '0000100003%' OR TypeID LIKE '0000100004%')
            		AND	parid  =  @szTypeid 
            		and 	deleted = 0
            		AND 	p.fullname LIKE '%' + @szFullName + '%'
                        AND 	usercode LIKE '%' + @szUserCode + '%'
			and     deleted = 0
		END
	RETURN 
	END
END
    IF @cMode = 'A' 
        IF @SearchFlag = 1 
            SELECT  Typeid AS Atypeid,
                    TYPEID,
                    PARID,
                    SONNUM,
                    USERCODE,
                    FULLNAME,
                    [NAME],
                    NAMEPY,
                    COMMENT,
                    CASE WHEN @BranchId = '0000100001' THEN '00001'
                         ELSE branchid
                    END AS branchid,
                    rec,
                    0 AS paridstop
            FROM    FN_GetPowerRangeAList(@OperatorID, @szTypeid,@BranchId) p
            WHERE   DELETED = 0
                    AND ( p.fullname LIKE '%' + @szFullName + '%'
                          AND usercode LIKE '%' + @szUserCode + '%'
                        )
            ORDER BY CASE WHEN @con = 0 THEN TYPEID
                          ELSE usercode
                     END  
        ELSE 
        	IF LEFT(@szTypeid,10)='0000100003' OR LEFT(@szTypeid,10)='0000100004'
        		SET @cMode = 'AA' 
        	ELSE
            SELECT  Typeid AS Atypeid,
                    TYPEID,
                    PARID,
                    SONNUM,
                    USERCODE,
                    FULLNAME,
                    [NAME],
                    NAMEPY,
                    COMMENT,
                    CASE WHEN @BranchId = '0000100001' THEN '00001'
                         ELSE branchid
                    END AS branchid,
                    rec,
                    0 AS paridstop
            FROM    FN_GetPowerRangeATree(@OperatorID, @szTypeid,@BranchId) p
            WHERE   parid = @szTypeid
                    AND DELETED = 0
                    AND ( p.fullname LIKE '%' + @szFullName + '%'
                          AND usercode LIKE '%' + @szUserCode + '%'
                        )
                       
            ORDER BY CASE WHEN @con = 0 THEN TYPEID
                          ELSE usercode
                     END 

--银行 + 现金
    IF @cMode = 'AA' 
        IF @szTypeid = '00001' 
            IF @SearchFlag = 1 
                SELECT  Typeid AS Atypeid,
                        TYPEID,
                        PARID,
                        SONNUM,
                        USERCODE,
                        FULLNAME,
                        [NAME],
                        NAMEPY,
                        COMMENT,
                        CASE WHEN @BranchId = '0000100001' THEN '00001'
                             ELSE branchid
                        END AS branchid,
                        rec,
                        0 AS paridstop
                FROM    FN_GetPowerRangeAList(@OperatorID, @szTypeid,@BranchId) p
                WHERE   ( typeid LIKE '0000100003%'
                          OR Typeid LIKE '0000100004%'
                        )
                        AND sonnum = 0
                        AND LEFT(typeid, LEN(@szTypeid)) = @szTypeid
                        AND DELETED = 0
                        AND ( p.fullname LIKE '%' + @szFullName + '%'
                              AND usercode LIKE '%' + @szUserCode + '%'
                            )
                        AND BranchID LIKE @BranchId + '%'
                ORDER BY CASE WHEN @con = 0 THEN TYPEID
                              ELSE usercode
                         END  
            ELSE 
                SELECT  Typeid AS Atypeid,
                        TYPEID,
                        PARID,
                        SONNUM,
                        USERCODE,
                        FULLNAME,
                        [NAME],
                        NAMEPY,
                        COMMENT,
                        CASE WHEN @BranchId = '0000100001' THEN '00001'
                             ELSE branchid
                        END AS branchid,
                        rec,
                        0 AS paridstop
                FROM    FN_GetPowerRangeATree(@OperatorID, @szTypeid,@BranchId) p
                WHERE   ( typeid LIKE '0000100003%'
                          OR Typeid LIKE '0000100004%'
                        )
                        AND parid = @szTypeid
                        
                        AND DELETED = 0
                        AND ( p.fullname LIKE '%' + @szFullName + '%'
                              AND usercode LIKE '%' + @szUserCode + '%'
                            )
                        AND BranchID LIKE @BranchId + '%'
                ORDER BY CASE WHEN @con = 0 THEN TYPEID
                              ELSE usercode
                         END 
        ELSE 
            IF @SearchFlag = 1 
                SELECT  Typeid AS Atypeid,
                        TYPEID,
                        PARID,
                        SONNUM,
                        USERCODE,
                        FULLNAME,
                        [NAME],
                        NAMEPY,
                        COMMENT,
                        CASE WHEN @BranchId = '0000100001' THEN '00001'
                             ELSE branchid
                        END AS branchid,
                        rec,
                        0 AS paridstop
                FROM    FN_GetPowerRangeAList(@OperatorID, @szTypeid,@BranchId) p
                WHERE   sonnum = 0
                        AND LEFT(typeid, LEN(@szTypeid)) = @szTypeid
                        AND DELETED = 0
                        AND ( p.fullname LIKE '%' + @szFullName + '%'
                              AND usercode LIKE '%' + @szUserCode + '%'
                            )
                        AND BranchID LIKE @BranchId + '%'
                ORDER BY CASE WHEN @con = 0 THEN TYPEID
                              ELSE usercode
                         END  
            ELSE 
                SELECT  Typeid AS Atypeid,
                        TYPEID,
                        PARID,
                        SONNUM,
                        USERCODE,
                        FULLNAME,
                        [NAME],
                        NAMEPY,
                        COMMENT,
                        CASE WHEN @BranchId = '0000100001' THEN '00001'
                             ELSE branchid
                        END AS branchid,
                        rec,
                        0 AS paridstop
                FROM    FN_GetPowerRangeATree(@OperatorID, @szTypeid,@BranchId) p
                WHERE   parid = @szTypeid
                        AND DELETED = 0
                        AND ( p.fullname LIKE '%' + @szFullName + '%'
                              AND usercode LIKE '%' + @szUserCode + '%'
                            )
                        AND BranchID LIKE @BranchId + '%'
                ORDER BY CASE WHEN @con = 0 THEN TYPEID
                              ELSE usercode
                         END  


    IF @cMode = 'B' 
        IF @SearchFlag = 0 
            SELECT  b.typeid AS btypeid,
                    B.TYPEID,
                    B.PARID,
                    B.SONNUM,
                    B.USERCODE,
                    B.FULLNAME,
                    B.[NAME],
                    B.NAMEPY,
                    B.COMMENT,
                    B.POSTCODE,
                    B.PERSON,
                    B.TAXNo,
                    B.FAXno,
                    B.BANK,
                    B.Account,
                    B.ADDRESS,
                    b.Tel1,
                    b.tel2,
                    b.netaddress,
                    b.email,
                    b.CheckAndAccept,
                    b.BarterRate,
                    b.BarterTerm,
                    b.usertype,
                    b.branchid,
                    b.[Stop],
		    Case b.[stop] when 1 then '√' else ' ' end as StopMark,
                    --0 AS paridstop
                    ISNULL(( SELECT TOP 1
                                    [stop]
                             FROM   dbo.Btype
                             WHERE  typeid = @szTypeid
                           ), 0) AS paridstop
                           ,b.Person+b.Tel2 as persona 
                           ,b.Personb+b.Telb as personb
                           ,b.Personc+b.Telc as personc,b.wuliu
            FROM    FN_GetPowerRangeBTree(@OperatorID, @szTypeid,
                                          '1,2,3,4,6,7') B
            WHERE   ( ( @SearchFlag = 1
                        AND sonnum = 0
                        AND LEFT(typeid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND parid = @szTypeid
                         )
                    )
                    AND DELETED = 0
                    AND BranchID LIKE @BranchId + '%'
                    AND 
                    (
                    		BranchID like '00001%'
                    		OR
                    		(
                    			BranchID LIKE '00004%'
                    			AND
                    			BranchID IN ( SELECT BranchID FROM dbo.FN_GetPowerRangeBCList(@OperatorID  ,@BranchID ) )
                    		)
												OR
												(
													exists(select * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZCS')													
												)
                    )
                    AND ( fullname LIKE '%' + @szFullName + '%'
                          AND usercode LIKE '%' + @szUserCode + '%'
                        )
            ORDER BY CASE WHEN @con = 0 THEN TYPEID
                          ELSE usercode
                     END  
	
        ELSE 
            SELECT  b.typeid AS btypeid,
                    B.TYPEID,
                    B.PARID,
                    B.SONNUM,
                    B.USERCODE,
                    B.FULLNAME,
                    B.[NAME],
                    B.NAMEPY,
                    B.COMMENT,
                    B.POSTCODE,
                    B.PERSON,
                    B.TAXNo,
                    B.FAXno,
                    B.BANK,
                    B.Account,
                    B.ADDRESS,
                    b.Tel1,
                    b.tel2,
                    b.netaddress,
                    b.email,
                    b.CheckAndAccept,
                    b.BarterRate,
                    b.BarterTerm,
                    b.usertype,
                    b.branchid,
                    b.[Stop],
		    Case b.[stop] when 1 then '√' else ' ' end as StopMark,
                    --0 AS paridstop
                    ISNULL(( SELECT TOP 1
                                    [stop]
                             FROM   dbo.Btype
                             WHERE  typeid = @szTypeid
                           ), 0) AS paridstop,b.Person+' '+b.Tel2 as persona 
                           ,b.Personb+' '+b.Telb as personb
                           ,b.Personc+' '+b.Telc as personc,b.wuliu
            FROM    FN_GetPowerRangeBList(@OperatorID, @szTypeid,
                                          '1,2,3,4,6,7') B
            WHERE   ( ( @SearchFlag = 1
                        AND sonnum = 0
                        AND LEFT(typeid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND parid = @szTypeid
                         )
                    )
                    AND DELETED = 0
                    AND BranchID LIKE @BranchId + '%'
                    AND 
                    (
                    		BranchID like '00001%'
                    		OR
                    		(
                    			BranchID LIKE '00004%'
                    			AND
                    			BranchID IN ( SELECT BranchID FROM dbo.FN_GetPowerRangeBCList(@OperatorID  ,@BranchID ) )
                    		)
												OR
												(
													exists(select * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZCS')													
												)
                    )
                    AND ( fullname LIKE '%' + @szFullName + '%'
                          AND usercode LIKE '%' + @szUserCode + '%'
                        )
            ORDER BY CASE WHEN @con = 0 THEN TYPEID
                          ELSE usercode
                     END  


    IF @cMode = 'BC' 
        IF @SearchFlag = 0 
            SELECT  b.Branchid AS bCtypeid,
                    B.Branchid,
                    B.PARID,
                    B.SONNUM,
                    B.USERCODE,
                    B.FULLNAME,
                    B.[NAME],
                    B.NAMEPY,
                    B.COMMENT,
                    B.ADDRESS,
                    b.Tel,
                    b.email,
                    b.btypeid,
                    b.BranchType,
                    b.checkandaccept,
                    0 AS paridstop
            FROM    FN_GetPowerRangeBCTree(@OperatorID, @szTypeid) B
            WHERE   ( ( @SearchFlag = 1
                        AND sonnum = 0
                        AND LEFT(Branchid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND ( parid = @szTypeid )
                         )
                    )
                    AND DELETED = 0
                    AND ( fullname LIKE '%' + @szFullName + '%'
                          AND usercode LIKE '%' + @szUserCode + '%'
                        )
            ORDER BY CASE WHEN @con = 0 THEN Branchid
                          ELSE usercode
                     END  
        ELSE 
            SELECT  b.Branchid AS bCtypeid,
                    B.Branchid,
                    B.PARID,
                    B.SONNUM,
                    B.USERCODE,
                    B.FULLNAME,
                    B.[NAME],
                    B.NAMEPY,
                    B.COMMENT,
                    B.ADDRESS,
                    b.Tel,
                    b.email,
                    b.btypeid,
                    b.BranchType,
                    b.checkandaccept,
                    0 AS paridstop
            FROM    FN_GetPowerRangeBCList(@OperatorID, @szTypeid) B
            WHERE   ( ( @SearchFlag = 1
                        AND sonnum = 0
                        AND LEFT(Branchid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND ( parid = @szTypeid )
                         )
                    )
                    AND DELETED = 0
                    AND ( fullname LIKE '%' + @szFullName + '%'
                          AND usercode LIKE '%' + @szUserCode + '%'
                        )
            ORDER BY CASE WHEN @con = 0 THEN Branchid
                          ELSE usercode
                     END  

    IF @cMode = 'D' 
        SELECT  typeid AS dtypeid,
                TYPEID,
                PARID,
                SONNUM,
                USERCODE,
                FULLNAME,
                NAMEPY,
                COMMENT,
                branchid,
                0 AS paridstop
        FROM    DEPARTMENT
        WHERE   PARID = @szTypeid
                AND DELETED = 0
                AND BranchID LIKE @BranchId + '%'
                AND 
                (
                	BranchID = '00001'
                	OR
                	BranchID IN ( SELECT BranchID FROM dbo.FN_GetPowerRangeBCList( @OperatorID ,'') )	--qf 2011-11-16  加盟部门受权限控制
                )
        ORDER BY CASE WHEN @con = 0 THEN TYPEID
                          ELSE USERCODE
                     END  
    IF @cMode = 'E'
    --特殊说明下，职员选择时@szBarCode代表的职员所属的机构Id
        IF @SearchFlag = 0 
            SELECT  E.TYPEID,
                    E.TYPEID AS ETYPEID,
                    E.PARID,
                    E.SONNUM,
                    E.USERCODE,
                    E.FULLNAME,
                    E.[NAME],
                    E.NAMEPY,
                    E.COMMENT,
                    E.dtypeid,
                    ISNULL(D.FULLNAME, '') AS EDEPT,
                    E.TEL,
                    E.ADDRESS,
                    E.ZkPopedom,
                    E.YHPopedom,
                    E.isShopSale,
                    E.branchid,
                    E.Branchid AS bCtypeid,
                    E.[Stop],
		    Case E.[stop] when 1 then '√' else ' ' end as StopMark,
                    ISNULL(( SELECT TOP 1
                                    [stop]
                             FROM   dbo.Employee
                             WHERE  typeid = @szTypeid
                           ), 0) AS paridstop
                    --0 AS paridstop
            FROM    FN_GetPowerRangeETree(@OperatorID, @szTypeid) E
                    LEFT OUTER JOIN DEPARTMENT D ON E.dtypeid = D.TYPEID
            WHERE   ( ( @SearchFlag = 1
                        AND e.sonnum = 0
                        AND LEFT(e.typeid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND e.parid = case when @szTypeid='00000' then '0' when @szTypeid='' then '00000' else @szTypeid end
                         )
                    )
                    AND e.DELETED = 0 
				--and e.BranchId=case when @szBarCode='' then e.BranchId else @szBarCode end
                    AND e.branchID LIKE @BranchId + '%'
                    AND 
                    (
                    		e.BranchID like '00001%'
                    		OR
                    		(
                    			e.BranchID LIKE '00004%'
                    			AND
                    			e.BranchID IN ( SELECT BranchID FROM dbo.FN_GetPowerRangeBCList(@OperatorID  ,@BranchID ) )
                    		)
                    )
                    AND ( e.fullname LIKE '%' + @szFullName + '%'
                          AND e.usercode LIKE '%' + @szUserCode + '%'
                        )
            ORDER BY CASE WHEN @con = 0 THEN e.TYPEID
                          ELSE e.usercode
                     END  
        ELSE 
            SELECT  E.TYPEID,
                    E.TYPEID AS ETYPEID,
                    E.PARID,
                    E.SONNUM,
                    E.USERCODE,
                    E.FULLNAME,
                    E.[NAME],
                    E.NAMEPY,
                    E.COMMENT,
                    E.dtypeid,
                    ISNULL(D.FULLNAME, '') AS EDEPT,
                    E.TEL,
                    E.ADDRESS,
                    E.ZkPopedom,
                    E.YHPopedom,
                    E.isShopSale,
                    E.branchid,
                    E.Branchid AS bCtypeid,
                    E.[Stop],
		    Case E.[stop] when 1 then '√' else ' ' end as StopMark,
                    ISNULL(( SELECT TOP 1
                                    [stop]
                             FROM   dbo.Employee
                             WHERE  typeid = @szTypeid
                           ), 0) AS paridstop
                    --0 AS paridstop
            FROM    FN_GetPowerRangeEList(@OperatorID, @szTypeid) E
                    LEFT OUTER JOIN DEPARTMENT D ON E.dtypeid = D.TYPEID
            WHERE   ( ( @SearchFlag = 1
                        AND e.sonnum = 0
                        AND e.typeid <> '00000'
                        AND LEFT(e.typeid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND e.parid = @szTypeid
                         )
                    )
                    AND e.DELETED = 0 
				--and e.BranchId=case when @szBarCode='' then e.BranchId else @szBarCode end
                    AND e.branchID LIKE @BranchId + '%'
                    AND 
                    (
                    		e.BranchID like '00001%'
                    		OR
                    		(
                    			e.BranchID LIKE '00004%'
                    			AND
                    			e.BranchID IN ( SELECT BranchID FROM dbo.FN_GetPowerRangeBCList(@OperatorID  ,@BranchID ) )
                    		)
                    )
                    AND ( e.fullname LIKE '%' + @szFullName + '%'
                          AND e.usercode LIKE '%' + @szUserCode + '%'
                        )
            ORDER BY CASE WHEN @con = 0 THEN e.TYPEID
                          ELSE e.usercode
                     END  
	  
	  
    IF @cMode = 'K' 
        BEGIN
            IF @BranchId = '00000' 
                SET @BranchId = ''
            IF @szTypeid = '' 
                SELECT  TYPEID,
                        TYPEID AS Ktypeid,
                        PARID,
                        SONNUM,
                        USERCODE,
                        FULLNAME,
                        [NAME],
                        NAMEPY,
                        COMMENT,
                        Branchid,
												BranchId as BCTypeId,
                        branchType,
                        0 AS paridstop,
                        isdefault,
                        CASE WHEN isdefault = 1 THEN '√'
                             ELSE ''
                        END AS dkfullname
                FROM    stock p
                WHERE   ( ( @SearchFlag = 1
                            AND sonnum = 0
                          )
                          OR (@SearchFlag = 0 and parid not in (select typeid from stock where sonnum > 0 and [leveal] > 0))
                        )
                        AND typeid <> '99999'
                        AND typeid <> '00000'
                        AND EXISTS (
                        SELECT  1
                        FROM   dbo.FN_GetStockListOfBranchIni(@OperatorID,@branchid,'') slb WHERE slb.KtypeId like p.TypeID + '%' )
                        AND DELETED = 0 and BranchId in (Select BranchID from Branch where sonnum = 0 and Deleted = 0)
                        AND ( p.fullname LIKE '%' + @szFullName + '%'
                              AND usercode LIKE '%' + @szUserCode + '%'
                            )  --and len(typeid) > 5 
                ORDER BY CASE WHEN @con = 0 THEN BranchId
                              ELSE usercode
                         END,
                        usercode
            ELSE 
                SELECT  TYPEID,
                        TYPEID AS Ktypeid,
                        PARID,
                        SONNUM,
                        USERCODE,
                        FULLNAME,
                        [NAME],
                        NAMEPY,
                        COMMENT,
                        Branchid,
												BranchId as bctypeId,
                        branchType,
                        isdefault,
                        CASE WHEN isdefault = 1 THEN '√'
                             ELSE ''
                        END AS dkfullname
                FROM    stock p
                WHERE   ( ( @SearchFlag = 1
                            AND sonnum = 0
                          )
                          OR (@SearchFlag <> 1
													AND (exists(select * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZBS') or ((@szTypeid = '00000' and
												    parid not in (select typeid from stock where sonnum > 0 and [leveal] > 0)))
													  or (@szTypeid <> '00000' and parid = @szTypeid )))
                        )
												AND (exists(select * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZCS') or p.parid = @szTypeid)
--@szTypeid=case @szTypeid when '00001' then p.parid else left(p.parid, len(@szTypeid)) end
                        AND typeid <> '99999'
                        AND typeid <> '00000' and BranchId in (Select BranchID from Branch where sonnum = 0 and Deleted = 0)
                        AND EXISTS (
                        SELECT  1
                        FROM   dbo.FN_GetStockListOfBranchIni(@OperatorID,@branchid,'') slb WHERE slb.KtypeId like p.TypeID + '%')
                        AND DELETED = 0
                        AND ( p.fullname LIKE '%' + @szFullName + '%'
                              AND usercode LIKE '%' + @szUserCode + '%'
                            ) -- and len(typeid) > 5 
                ORDER BY CASE WHEN @con = 0 THEN BranchId
                              ELSE usercode
                         END,
                        usercode

        END
    IF @cMode = 'P' 
        IF @SearchFlag = 0 
            SELECT  TYPEID,
                    typeid AS ptypeid,
                    PARID,
                    SONNUM,
                    p.USERCODE,
                    FULLNAME,
                    p.USERCODE AS pusercode,p.FULLNAME AS pfullname,
                    p.NAME,
                    NAMEPY,
                    p.COMMENT,
                    STANDARD,
                    TYPE,
                    AREA,
                    UNIT1,
                    UNIT2,
                    UNITRATE1,
                    CASE COSTMODE
                      WHEN 0 THEN '加权平均法'
                      WHEN 1 THEN '先进先出法'
                      WHEN 2 THEN '后进先出法'
                      WHEN 3 THEN '手工指定法'
                    END AS Costmode,
                    BARCODE,
                    Stop,
		    Case [stop] when 1 then '√' else ' ' end as StopMark,
                    retailPrice,
                    bar.PlanDetail AS formatid,
                    CSPZ,
                    trade,
                    IssueDate,
                    BREAKWARN,
                    ISNULL(( SELECT TOP 1
                                    stop
                             FROM   ptype
                             WHERE  typeid = @szTypeid
                           ), 0) AS paridstop,
                    ChangeRule
            FROM    FN_GetPowerRangePTree(@OperatorID, @szTypeid) P,
                    dbo.BarCodePlan bar
            WHERE   ( ( @SearchFlag = 1
                        AND sonnum = 0
                        AND LEFT(typeid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND parid = @szTypeid
                         )
                    )
                    AND p.FormatID = CAST(bar.PlanId AS VARCHAR)
                    AND DELETED = 0
                    AND typeid <> '00000'
                    AND ( p.fullname LIKE '%' + @szFullName + '%'
                          AND p.usercode LIKE '%' + @szUserCode + '%'
                          AND p.StopDate LIKE @szStopDate + '%'
                          AND p.BarCode LIKE '%' + @szBarCode + '%'
                          AND p.name LIKE '%' + @szName + '%'
                          AND p.IssueDate LIKE @szIssueDate + '%'
                        )
            ORDER BY CASE WHEN @con = 1 THEN p.usercode
                          ELSE RIGHT('0000000000' + CAST(p.porder AS VARCHAR),
                                     10)
                     END,
                    typeid  
  
        ELSE 
            SELECT  TYPEID,
                    typeid AS ptypeid,
                    PARID,
                    SONNUM,
                    p.USERCODE,
                    FULLNAME,
                    p.USERCODE AS pusercode,p.FULLNAME AS pfullname,
                    p.NAME,
                    NAMEPY,
                    p.COMMENT,
                    STANDARD,
                    TYPE,
                    AREA,
                    UNIT1,
                    UNIT2,
                    UNITRATE1,
                    CASE COSTMODE
                      WHEN 0 THEN '加权平均法'
                      WHEN 1 THEN '先进先出法'
                      WHEN 2 THEN '后进先出法'
                      WHEN 3 THEN '手工指定法'
                    END AS Costmode,
                    BARCODE,
                    Stop,
		    Case [stop] when 1 then '√' else ' ' end as StopMark,
                    retailPrice,
                    bar.PlanDetail AS formatid,
                    CSPZ,
                    trade,
                    IssueDate,
                    BREAKWARN,
                    0 AS paridstop,
                    ChangeRule
            FROM    FN_GetPowerRangePList(@OperatorID, @szTypeid) P,
                    dbo.BarCodePlan bar
            WHERE   ( ( @SearchFlag = 1
                        AND sonnum = 0
                        AND LEFT(typeid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND parid = @szTypeid
                         )
                    )
                    AND p.FormatID = CAST(bar.PlanId AS VARCHAR)
                    AND DELETED = 0
                    AND typeid <> '00000'
                    AND ( p.fullname LIKE '%' + @szFullName + '%'
                          AND p.usercode LIKE '%' + @szUserCode + '%'
                          AND p.StopDate LIKE @szStopDate + '%'
                          AND p.BarCode LIKE '%' + @szBarCode + '%'
                          AND p.name LIKE '%' + @szName + '%'
                          AND p.IssueDate LIKE @szIssueDate + '%'
                        )
            ORDER BY CASE WHEN @con = 1 THEN p.usercode
                          ELSE RIGHT('0000000000' + CAST(p.porder AS VARCHAR),
                                     10)
                     END,
                    typeid  

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/****** Object:  StoredProcedure [dbo].[FzGetAllPowerPro]    Script Date: 03/13/2012 16:01:35 ******/
IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[FZGetAllJXC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].FZGetAllJXC
GO


/****** Object:  StoredProcedure [dbo].[FZGetAllJXC]    Script Date: 03/13/2012 16:01:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].FZGetAllJXC
(
      @BranchId varchar(8000) ,
      @PtypeId varchar(50) ,
      @KtypeId varchar(8000) ,
      @DateBegin varchar(15) ,
      @DateEnd varchar(15) ,
      @Displaymode int ,
      @OperatorId VARCHAR(50),
      @OnlyCheckChange bit = 0
)
as
begin

	Declare @NdxMaxId int
	Declare @QryMaxId int
	select @NdxMaxId = MAX(vchcode) from dlyndx
	select @QryMaxId = cast(subvalue as int) from QueryVchcodeRec where subname = 'AllPowerMaxVch'
	--新增存储过程 GetDig，用来取小数配置。以后所有报表存储过程对小数位的取舍用以下方式。
    DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
    EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
	
	if (@NdxMaxId > @QryMaxId) or exists(select 1 from TBAllPowerChangeVchcode where vchcode <= @QryMaxId)
	begin
	        if object_id('tempdb..#InoutVchTypeTemp') is not null 
	        	drop table #InoutVchTypeTemp
		Delete from TBAllPowerChangeVchcode where vchcode > @QryMaxId		
		Create Table #InoutVchTypeTemp
		(
		 VchType int,
		 DetailType int,
		 Phid int
		)
			insert into #InoutVchTypeTemp select vchtype,detailtype,phid from 
			(Select 34 as vchtype,101 as detailtype,0 as phid union all
			Select 45 as vchtype,102 as detailtype,0 as phid union all
			Select 101 as vchtype,102 as detailtype,0 as phid union all
			Select 16 as vchtype,103 as detailtype,0 as phid union all
			Select 14 as vchtype,104 as detailtype,0 as phid union all		
			Select 126 as vchtype,105 as detailtype,0 as phid union all
			Select 17 as vchtype,106 as detailtype,0 as phid union all
			Select 21 as vchtype,107 as detailtype,0 as phid union all
			Select 24 as vchtype,108 as detailtype,0 as phid union all
			Select 57 as vchtype,109 as detailtype,0 as phid union all
			Select 13 as vchtype,112 as detailtype,0 as phid union all
			Select 101 as vchtype,112 as detailtype,0 as phid union all
			Select 100 as vchtype,112 as detailtype,0 as phid union all
			Select 12 as vchtype,112 as detailtype,0 as phid union all
			Select 212 as vchtype,113 as detailtype,1 as phid union all
			Select 218 as vchtype,113 as detailtype,1 as phid union all
			Select 212 as vchtype,113 as detailtype,3 as phid union all
			Select 218 as vchtype,113 as detailtype,3 as phid union all
			Select 224 as vchtype,115 as detailtype,0 as phid union all
			Select 230 as vchtype,116 as detailtype,0 as phid union all
			Select 212 as vchtype,118 as detailtype,2 as phid union all
			Select 218 as vchtype,118 as detailtype,2 as phid union all
			Select 150 as vchtype,120 as detailtype,0 as phid union all
			Select 252 as vchtype,121 as detailtype,0 as phid union all
			Select 11 as vchtype,201 as detailtype,0 as phid union all
			Select 6 as vchtype,202 as detailtype,0 as phid union all
			Select 16 as vchtype,203 as detailtype,0 as phid union all
			Select 139 as vchtype,204 as detailtype,0 as phid union all
			Select 17 as vchtype,205 as detailtype,0 as phid union all
			Select 9 as vchtype,206 as detailtype,0 as phid union all
			Select 21 as vchtype,207 as detailtype,0 as phid union all
			Select 24 as vchtype,208 as detailtype,0 as phid union all
			Select 57 as vchtype,209 as detailtype,0 as phid union all
			Select 13 as vchtype,212 as detailtype,0 as phid union all
			Select 101 as vchtype,212 as detailtype,0 as phid union all
			Select 100 as vchtype,212 as detailtype,0 as phid union all
			Select 12 as vchtype,212 as detailtype,0 as phid union all
			Select 212 as vchtype,213 as detailtype,1 as phid union all
			Select 212 as vchtype,213 as detailtype,3 as phid union all
			Select 218 as vchtype,213 as detailtype,1 as phid union all
			Select 218 as vchtype,213 as detailtype,3 as phid union all
			Select 222 as vchtype,215 as detailtype,0 as phid union all
			Select 224 as vchtype,215 as detailtype,0 as phid union all
			Select 230 as vchtype,216 as detailtype,0 as phid union all
			Select 212 as vchtype,218 as detailtype,2 as phid union all
			Select 218 as vchtype,218 as detailtype,2 as phid union all
			Select 150 as vchtype,220 as detailtype,0 as phid union all
			Select 251 as vchtype,221 as detailtype,0 as phid
			) a	

		Insert into TableForAllJXC select a.phid,b.PtypeId,c.ColorID,c.SizeID,b.BranchId,b.ktypeId,CONVERT(NUMERIC(24,10),sum(c.Qty)),CONVERT(NUMERIC(24,10),sum(c.CostTotal)),
		           CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END,
		           x.DetailType
		From DlyNdx a inner join DlyData b on a.Vchcode = b.Vchcode inner join dlydatadetail c on b.DlyOrder = c.DlyOrder --inner join #AllJXCKtypeIdTable f on b.KtypeId = f.KtypeId
			  Inner join #InoutVchTypeTemp x on a.Vchtype = x.VchType and x.Phid = a.PhId 
				--由于红冲单据的存在 所以出入库不能用正负号判断，故去掉
			 AND  
			 (
				(
					(
						(( c.qty > 0) and x.DetailType < 200) 
						OR  
						(( c.qty < 0) and x.DetailType > 200)
					) 
					AND a.RedWord = 'F'
				)
				OR
				(
					(
						(( c.qty > 0) and x.DetailType > 200) 
						OR  
						(( c.qty < 0) and x.DetailType < 200)
					) 
					AND a.RedWord = 'T'
				)
			)
			and ((b.Vchcode > @QryMaxId) or (b.vchcode in (select vchcode from TBAllPowerChangeVchcode) and ((b.ktypeid = '99999' and b.Qty < 0) or b.usedtype = 2)))
			----将新增单据数据以及验收的老单据数据写入表中
		group by a.phid,b.PtypeId,c.ColorID,c.SizeID ,b.BranchId,b.ktypeId ,a.date,x.DetailType
		Order by a.date				
		drop table #InoutVchTypeTemp
		Update QueryVchcodeRec set subvalue = cast(@NdxMaxId as varchar) where subname = 'AllPowerMaxVch'		
		Delete from TBAllPowerChangeVchcode where vchcode <= @QryMaxId		
	end
		
    if object_id('tempdb..#AllJXCKtypeIdTable') is not null 
        drop table #AllJXCKtypeIdTable
    if object_id('tempdb..#AllJXCPtypeIdTable') is not null 
        drop table #AllJXCPtypeIdTable        
        
    select  KtypeId
    Into    #AllJXCKtypeIdTable
    from    FN_GetStockListOfBranch(@OperatorID, @BranchId, @Ktypeid) a
    where   exists ( select 1
                     from   Stock b
                     where  a.ktypeid = b.typeid
                            and b.branchtype <> 4 )
	create CLUSTERED index TempIdx1 on #AllJXCKtypeIdTable(Ktypeid)                             

	Select typeId,retailPrice
	Into #AllJXCPtypeIdTable
	from FN_GetPowerRangePList(@OperatorId, @PtypeId) a
        where @OnlyCheckChange = 0 or (@OnlyCheckChange = 1 and exists (Select 1 from TableForAllJXC x where Datadate between @DateBegin and @DateEnd and a.typeId = x.PtypeId)) 
	
	create CLUSTERED index TempIdx2 on #AllJXCPtypeIdTable(typeId)                    
	
    if @DisplayMode = 0 
        begin
			select Ptypeid,case when (detailtype > 200 and detailtype < 300) then -SUM(Qty) else SUM(Qty) end as qty,
				case when (detailtype > 200 and detailtype < 300) then -SUM(CostTotal) else SUM(CostTotal) end as costtotal,	detailtype,
						CASE WHEN (detailtype > 200 and detailtype < 300) THEN -sum(RetailTotal) ELSE sum(RetailTotal) END as RetailTotal into #TempAllJXC1 from 
				(select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	detailtype,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as RetailTotal from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate between @DateBegin and @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,Left(PtypeId, Len(@PtypeId) + 5)
				union all
				select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,-SUM(Qty) as qty,-SUM(CostTotal) as costtotal,	401,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),-Qty)*CONVERT(NUMERIC(24,10),c.RetailPrice))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate > @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,Left(PtypeId, Len(@PtypeId) + 5) 
				union all
				select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	301,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate < @DateBegin
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by Left(PtypeId, Len(@PtypeId) + 5)
				union all (select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(qty) as qty,SUM(total) as costtotal,301 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from IniGoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by Left(PtypeId, Len(@PtypeId) + 5))
				union all (select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(qty) as qty,SUM(total) as costtotal,401 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from GoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by Left(PtypeId, Len(@PtypeId) + 5))						
				) a
				group by PtypeId,DetailType



				
            select  PtypeId ,
                                      isnull(sum(case DetailType
                                 when 101 then Qty
                                 else 0
                               end), 0) as Qty101 ,
                    isnull(sum(case DetailType
                                 when 101 then CostTotal
                                 else 0
                               end), 0) as Total101 ,
                    isnull(sum(case DetailType
                                 when 101 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal101 ,
                    isnull(sum(case DetailType
                                 when 102 then Qty
                                 else 0
                               end), 0) as Qty102 ,
                    isnull(sum(case DetailType
                                 when 102 then CostTotal
                                 else 0
                               end), 0) as Total102 ,
                    isnull(sum(case DetailType
                                 when 102 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal102 ,
                    isnull(sum(case DetailType
                                 when 103 then Qty
                                 else 0
                               end), 0) as Qty103 ,
                    isnull(sum(case DetailType
                                 when 103 then CostTotal
                                 else 0
                               end), 0) as Total103 ,
                    isnull(sum(case DetailType
                                 when 103 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal103 ,
                    isnull(sum(case DetailType
                                 when 104 then Qty
                                 else 0
                               end), 0) as Qty104 ,
                    isnull(sum(case DetailType
                                 when 104 then CostTotal
                                 else 0
                               end), 0) as Total104 ,
                    isnull(sum(case DetailType
                                 when 104 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal104 ,
                    isnull(sum(case DetailType
                                 when 105 then Qty
                                 else 0
                               end), 0) as Qty105 ,
                    isnull(sum(case DetailType
                                 when 105 then CostTotal
                                 else 0
                               end), 0) as Total105 ,
                    isnull(sum(case DetailType
                                 when 105 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal105 ,
                    isnull(sum(case DetailType
                                 when 106 then Qty
                                 else 0
                               end), 0) as Qty106 ,
                    isnull(sum(case DetailType
                                 when 106 then CostTotal
                                 else 0
                               end), 0) as Total106 ,
                    isnull(sum(case DetailType
                                 when 106 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal106 ,
                    isnull(sum(case DetailType
                                 when 107 then Qty
                                 else 0
                               end), 0) as Qty107 ,
                    isnull(sum(case DetailType
                                 when 107 then CostTotal
                                 else 0
                               end), 0) as Total107 ,
                    isnull(sum(case DetailType
                                 when 107 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal107 ,
                    isnull(sum(case DetailType
                                 when 108 then Qty
                                 else 0
                               end), 0) as Qty108 ,
                    isnull(sum(case DetailType
                                 when 108 then CostTotal
                                 else 0
                               end), 0) as Total108 ,
                    isnull(sum(case DetailType
                                 when 108 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal108 ,
                    isnull(sum(case DetailType
                                 when 109 then Qty
                                 else 0
                               end), 0) as Qty109 ,
                    isnull(sum(case DetailType
                                 when 109 then CostTotal
                                 else 0
                               end), 0) as Total109 ,
                    isnull(sum(case DetailType
                                 when 109 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal109 ,
                    isnull(sum(case DetailType
                                 when 110 then Qty
                                 else 0
                               end), 0) as Qty110 ,
                    isnull(sum(case DetailType
                                 when 110 then CostTotal
                                 else 0
                               end), 0) as Total110 ,
                    isnull(sum(case DetailType
                                 when 110 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal110 ,
                    isnull(sum(case DetailType
                                 when 112 then Qty
                                 else 0
                               end), 0) as Qty112 ,
                    isnull(sum(case DetailType
                                 when 112 then CostTotal
                                 else 0
                               end), 0) as Total112 ,
                    isnull(sum(case DetailType
                                 when 112 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal112 ,
                    isnull(sum(case DetailType
                                 when 113 then Qty
                                 else 0
                               end), 0) as Qty113 ,
                    isnull(sum(case DetailType
                                 when 113 then CostTotal
                                 else 0
                               end), 0) as Total113 ,
                    isnull(sum(case DetailType
                                 when 113 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal113 ,
                    isnull(sum(case DetailType
                                 when 114 then Qty
                                 else 0
                               end), 0) as Qty114 ,
                    isnull(sum(case DetailType
                                 when 114 then CostTotal
                                 else 0
                               end), 0) as Total114 ,
                    isnull(sum(case DetailType
                                 when 114 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal114 ,
                    isnull(sum(case DetailType
                                 when 115 then Qty
                                 else 0
                               end), 0) as Qty115 ,
                    isnull(sum(case DetailType
                                 when 115 then CostTotal
                                 else 0
                               end), 0) as Total115 ,
                    isnull(sum(case DetailType
                                 when 115 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal115 ,
                    isnull(sum(case DetailType
                                 when 116 then Qty
                                 else 0
                               end), 0) as Qty116 ,
                    isnull(sum(case DetailType
                                 when 116 then CostTotal
                                 else 0
                               end), 0) as Total116 ,
                    isnull(sum(case DetailType
                                 when 116 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal116 ,
                    isnull(sum(case DetailType
                                 when 118 then Qty
                                 else 0
                               end), 0) as Qty118 ,
                    isnull(sum(case DetailType
                                 when 118 then CostTotal
                                 else 0
                               end), 0) as Total118 ,
                    isnull(sum(case DetailType
                                 when 118 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal118 ,
                    isnull(sum(case DetailType
                                 when 120 then Qty
                                 else 0
                               end), 0) as Qty120 ,
                    isnull(sum(case DetailType
                                 when 120 then CostTotal
                                 else 0
                               end), 0) as Total120 ,
                    isnull(sum(case DetailType
                                 when 120 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal120 ,
                    isnull(sum(case DetailType
                                 when 121 then Qty
                                 else 0
                               end), 0) as Qty121 ,
                    isnull(sum(case DetailType
                                 when 121 then CostTotal
                                 else 0
                               end), 0) as Total121 ,
                    isnull(sum(case DetailType
                                 when 121 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal121 ,
                    isnull(sum(case DetailType
                                 when 201 then Qty
                                 else 0
                               end), 0) as Qty201 ,
                    isnull(sum(case DetailType
                                 when 201 then CostTotal
                                 else 0
                               end), 0) as Total201 ,
                    isnull(sum(case DetailType
                                 when 201 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal201 ,
                    isnull(sum(case DetailType
                                 when 202 then Qty
                                 else 0
                               end), 0) as Qty202 ,
                    isnull(sum(case DetailType
                                 when 202 then CostTotal
                                 else 0
                               end), 0) as Total202 ,
                    isnull(sum(case DetailType
                                 when 202 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal202 ,
                    isnull(sum(case DetailType
                                 when 203 then Qty
                                 else 0
                               end), 0) as Qty203 ,
                    isnull(sum(case DetailType
                                 when 203 then CostTotal
                                 else 0
                               end), 0) as Total203 ,
                    isnull(sum(case DetailType
                                 when 203 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal203 ,
                    isnull(sum(case DetailType
                                 when 204 then Qty
                                 else 0
                               end), 0) as Qty204 ,
                    isnull(sum(case DetailType
                                 when 204 then CostTotal
                                 else 0
                               end), 0) as Total204 ,
                    isnull(sum(case DetailType
                                 when 204 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal204 ,
                    isnull(sum(case DetailType
                                 when 205 then Qty
                                 else 0
                               end), 0) as Qty205 ,
                    isnull(sum(case DetailType
                                 when 205 then CostTotal
                                 else 0
                               end), 0) as Total205 ,
                    isnull(sum(case DetailType
                                 when 205 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal205 ,
                    isnull(sum(case DetailType
                                 when 206 then Qty
                                 else 0
                               end), 0) as Qty206 ,
                    isnull(sum(case DetailType
                                 when 206 then CostTotal
                                 else 0
                               end), 0) as Total206 ,
                    isnull(sum(case DetailType
                                 when 206 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal206 ,
                    isnull(sum(case DetailType
                                 when 207 then Qty
                                 else 0
                               end), 0) as Qty207 ,
                    isnull(sum(case DetailType
                                 when 207 then CostTotal
                                 else 0
                               end), 0) as Total207 ,
                    isnull(sum(case DetailType
                                 when 207 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal207 ,
                    isnull(sum(case DetailType
                                 when 208 then Qty
                                 else 0
                               end), 0) as Qty208 ,
                    isnull(sum(case DetailType
                                 when 208 then CostTotal
                                 else 0
                               end), 0) as Total208 ,
                    isnull(sum(case DetailType
                                 when 208 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal208 ,
                    isnull(sum(case DetailType
                                 when 209 then Qty
                                 else 0
                               end), 0) as Qty209 ,
                    isnull(sum(case DetailType
                                 when 209 then CostTotal
                                 else 0
                               end), 0) as Total209 ,
                    isnull(sum(case DetailType
                                 when 209 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal209 ,
                    isnull(sum(case DetailType
                                 when 210 then Qty
                                 else 0
                               end), 0) as Qty210 ,
                    isnull(sum(case DetailType
                                 when 210 then CostTotal
                                 else 0
                               end), 0) as Total210 ,
                    isnull(sum(case DetailType
                                 when 210 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal210 ,
                    isnull(sum(case DetailType
                                 when 212 then Qty
                                 else 0
                               end), 0) as Qty212 ,
                    isnull(sum(case DetailType
                                 when 212 then CostTotal
                                 else 0
                               end), 0) as Total212 ,
                    isnull(sum(case DetailType
                                 when 212 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal212 ,
                    isnull(sum(case DetailType
                                 when 213 then Qty
                                 else 0
                               end), 0) as Qty213 ,
                    isnull(sum(case DetailType
                                 when 213 then CostTotal
                                 else 0
                               end), 0) as Total213 ,
                    isnull(sum(case DetailType
                                 when 213 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal213 ,
                    isnull(sum(case DetailType
                                 when 214 then Qty
                                 else 0
                               end), 0) as Qty214 ,
                    isnull(sum(case DetailType
                                 when 214 then CostTotal
                                 else 0
                               end), 0) as Total214 ,
                    isnull(sum(case DetailType
                                 when 214 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal214 ,
                    isnull(sum(case DetailType
                                 when 215 then Qty
                                 else 0
                               end), 0) as Qty215 ,
                    isnull(sum(case DetailType
                                 when 215 then CostTotal
                                 else 0
                               end), 0) as Total215 ,
                    isnull(sum(case DetailType
                                 when 215 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal215 ,
                    isnull(sum(case DetailType
                                 when 216 then Qty
                                 else 0
                               end), 0) as Qty216 ,
                    isnull(sum(case DetailType
                                 when 216 then CostTotal
                                 else 0
                               end), 0) as Total216 ,
                    isnull(sum(case DetailType
                                 when 216 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal216 ,
                    isnull(sum(case DetailType
                                 when 218 then Qty
                                 else 0
                               end), 0) as Qty218 ,
                    isnull(sum(case DetailType
                                 when 218 then CostTotal
                                 else 0
                               end), 0) as Total218 ,
                    isnull(sum(case DetailType
                                 when 218 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal218 ,
                    isnull(sum(case DetailType
                                 when 220 then Qty
                                 else 0
                               end), 0) as Qty220 ,
                    isnull(sum(case DetailType
                                 when 220 then CostTotal
                                 else 0
                               end), 0) as Total220 ,
                    isnull(sum(case DetailType
                                 when 220 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal220 ,
                    isnull(sum(case DetailType
                                 when 221 then Qty
                                 else 0
                               end), 0) as Qty221 ,
                    isnull(sum(case DetailType
                                 when 221 then CostTotal
                                 else 0
                               end), 0) as Total221 ,
                    isnull(sum(case DetailType
                                 when 221 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal221 ,
                    isnull(sum(case DetailType
                                 when 301 then Qty
                                 else 0
                               end), 0) as Qty301 ,
                    isnull(sum(case DetailType
                                 when 301 then CostTotal
                                 else 0
                               end), 0) as Total301 ,
                    isnull(sum(case DetailType
                                 when 301 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal301 ,
                    isnull(sum(case DetailType
                                 when 401 then Qty
                                 else 0
                               end), 0) as Qty401 ,
                    isnull(sum(case DetailType
                                 when 401 then CostTotal
                                 else 0
                               end), 0) as Total401 ,
                    isnull(sum(case DetailType
                                 when 401 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal401
            from    #TempAllJXC1 a --where not (DetailType = 301 and (qty = 0 or CostTotal = 0)) 		
            group by PtypeId
	end                    
	
	if @Displaymode = 1 
	begin	        
			select PtypeId,case when (detailtype > 200 and detailtype < 300) then -SUM(Qty) else SUM(Qty) end as qty,
					case when (detailtype > 200 and detailtype < 300) then -SUM(CostTotal) else SUM(CostTotal) end as costtotal,	detailtype,
						CASE WHEN (detailtype > 200 and detailtype < 300) THEN -sum(RetailTotal) ELSE sum(RetailTotal) END as RetailTotal into #TempAllJXC2 from 
				(select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	detailtype,
						ROUND(CONVERT(NUMERIC(24,10),SUM(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as RetailTotal from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate between @DateBegin and @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,PtypeId
				union all
				select PtypeId,-SUM(Qty) as qty,-SUM(CostTotal) as costtotal,	401,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),-Qty)*CONVERT(NUMERIC(24,10),c.RetailPrice))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate > @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,PtypeId
				union all
				select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	301,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate < @DateBegin
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId
				union all (select Ptypeid,SUM(qty) as qty,SUM(total) as costtotal,301 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from IniGoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId)
				union all (select Ptypeid,SUM(qty) as qty,SUM(total) as costtotal,401 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from GoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId						
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId)							
				) a
				group by PtypeId,DetailType
			
				
            select  PtypeId ,
		    --(SELECT TOP 1 [Order] FROM [dbo].[Size] si WHERE right('00000' + CAST(si.SizeId as VARCHAR), 5)  = pstypeid ) AS psOrder , 
                    isnull(sum(case DetailType
                                 when 101 then Qty
                                 else 0
                               end), 0) as Qty101 ,
                    isnull(sum(case DetailType
                                 when 101 then CostTotal
                                 else 0
                               end), 0) as Total101 ,
                    isnull(sum(case DetailType
                                 when 101 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal101 ,
                    isnull(sum(case DetailType
                                 when 102 then Qty
                                 else 0
                               end), 0) as Qty102 ,
                    isnull(sum(case DetailType
                                 when 102 then CostTotal
                                 else 0
                               end), 0) as Total102 ,
                    isnull(sum(case DetailType
                                 when 102 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal102 ,
                    isnull(sum(case DetailType
                                 when 103 then Qty
                                 else 0
                               end), 0) as Qty103 ,
                    isnull(sum(case DetailType
                                 when 103 then CostTotal
                                 else 0
                               end), 0) as Total103 ,
                    isnull(sum(case DetailType
                                 when 103 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal103 ,
                    isnull(sum(case DetailType
                                 when 104 then Qty
                                 else 0
                               end), 0) as Qty104 ,
                    isnull(sum(case DetailType
                                 when 104 then CostTotal
                                 else 0
                               end), 0) as Total104 ,
                    isnull(sum(case DetailType
                                 when 104 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal104 ,
                    isnull(sum(case DetailType
                                 when 105 then Qty
                                 else 0
                               end), 0) as Qty105 ,
                    isnull(sum(case DetailType
                                 when 105 then CostTotal
                                 else 0
                               end), 0) as Total105 ,
                    isnull(sum(case DetailType
                                 when 105 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal105 ,
                    isnull(sum(case DetailType
                                 when 106 then Qty
                                 else 0
                               end), 0) as Qty106 ,
                    isnull(sum(case DetailType
                                 when 106 then CostTotal
                                 else 0
                               end), 0) as Total106 ,
                    isnull(sum(case DetailType
                                 when 106 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal106 ,
                    isnull(sum(case DetailType
                                 when 107 then Qty
                                 else 0
                               end), 0) as Qty107 ,
                    isnull(sum(case DetailType
                                 when 107 then CostTotal
                                 else 0
                               end), 0) as Total107 ,
                    isnull(sum(case DetailType
                                 when 107 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal107 ,
                    isnull(sum(case DetailType
                                 when 108 then Qty
                                 else 0
                               end), 0) as Qty108 ,
                    isnull(sum(case DetailType
                                 when 108 then CostTotal
                                 else 0
                               end), 0) as Total108 ,
                    isnull(sum(case DetailType
                                 when 108 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal108 ,
                    isnull(sum(case DetailType
                                 when 109 then Qty
                                 else 0
                               end), 0) as Qty109 ,
                    isnull(sum(case DetailType
                                 when 109 then CostTotal
                                 else 0
                               end), 0) as Total109 ,
                    isnull(sum(case DetailType
                                 when 109 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal109 ,
                    isnull(sum(case DetailType
                                 when 110 then Qty
                                 else 0
                               end), 0) as Qty110 ,
                    isnull(sum(case DetailType
                                 when 110 then CostTotal
                                 else 0
                               end), 0) as Total110 ,
                    isnull(sum(case DetailType
                                 when 110 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal110 ,
                    isnull(sum(case DetailType
                                 when 112 then Qty
                                 else 0
                               end), 0) as Qty112 ,
                    isnull(sum(case DetailType
                                 when 112 then CostTotal
                                 else 0
                               end), 0) as Total112 ,
                    isnull(sum(case DetailType
                                 when 112 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal112 ,
                    isnull(sum(case DetailType
                                 when 113 then Qty
                                 else 0
                               end), 0) as Qty113 ,
                    isnull(sum(case DetailType
                                 when 113 then CostTotal
                                 else 0
                               end), 0) as Total113 ,
                    isnull(sum(case DetailType
                                 when 113 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal113 ,
                    isnull(sum(case DetailType
                                 when 114 then Qty
                                 else 0
                               end), 0) as Qty114 ,
                    isnull(sum(case DetailType
                                 when 114 then CostTotal
                                 else 0
                               end), 0) as Total114 ,
                    isnull(sum(case DetailType
                                 when 114 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal114 ,
                    isnull(sum(case DetailType
                                 when 115 then Qty
                                 else 0
                               end), 0) as Qty115 ,
                    isnull(sum(case DetailType
                                 when 115 then CostTotal
                                 else 0
                               end), 0) as Total115 ,
                    isnull(sum(case DetailType
                                 when 115 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal115 ,
                    isnull(sum(case DetailType
                                 when 116 then Qty
                                 else 0
                               end), 0) as Qty116 ,
                    isnull(sum(case DetailType
                                 when 116 then CostTotal
                                 else 0
                               end), 0) as Total116 ,
                    isnull(sum(case DetailType
                                 when 116 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal116 ,
                    isnull(sum(case DetailType
                                 when 118 then Qty
                                 else 0
                               end), 0) as Qty118 ,
                    isnull(sum(case DetailType
                                 when 118 then CostTotal
                                 else 0
                               end), 0) as Total118 ,
                    isnull(sum(case DetailType
                                 when 118 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal118 ,
                    isnull(sum(case DetailType
                                 when 120 then Qty
                                 else 0
                               end), 0) as Qty120 ,
                    isnull(sum(case DetailType
                                 when 120 then CostTotal
                                 else 0
                               end), 0) as Total120 ,
                    isnull(sum(case DetailType
                                 when 120 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal120 ,
                    isnull(sum(case DetailType
                                 when 121 then Qty
                                 else 0
                               end), 0) as Qty121 ,
                    isnull(sum(case DetailType
                                 when 121 then CostTotal
                                 else 0
                               end), 0) as Total121 ,
                    isnull(sum(case DetailType
                                 when 121 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal121 ,
                    isnull(sum(case DetailType
                                 when 201 then Qty
                                 else 0
                               end), 0) as Qty201 ,
                    isnull(sum(case DetailType
                                 when 201 then CostTotal
                                 else 0
                               end), 0) as Total201 ,
                    isnull(sum(case DetailType
                                 when 201 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal201 ,
                    isnull(sum(case DetailType
                                 when 202 then Qty
                                 else 0
                               end), 0) as Qty202 ,
                    isnull(sum(case DetailType
                                 when 202 then CostTotal
                                 else 0
                               end), 0) as Total202 ,
                    isnull(sum(case DetailType
                                 when 202 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal202 ,
                    isnull(sum(case DetailType
                                 when 203 then Qty
                                 else 0
                               end), 0) as Qty203 ,
                    isnull(sum(case DetailType
                                 when 203 then CostTotal
                                 else 0
                               end), 0) as Total203 ,
                    isnull(sum(case DetailType
                                 when 203 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal203 ,
                    isnull(sum(case DetailType
                                 when 204 then Qty
                                 else 0
                               end), 0) as Qty204 ,
                    isnull(sum(case DetailType
                                 when 204 then CostTotal
                                 else 0
                               end), 0) as Total204 ,
                    isnull(sum(case DetailType
                                 when 204 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal204 ,
                    isnull(sum(case DetailType
                                 when 205 then Qty
                                 else 0
                               end), 0) as Qty205 ,
                    isnull(sum(case DetailType
                                 when 205 then CostTotal
                                 else 0
                               end), 0) as Total205 ,
                    isnull(sum(case DetailType
                                 when 205 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal205 ,
                    isnull(sum(case DetailType
                                 when 206 then Qty
                                 else 0
                               end), 0) as Qty206 ,
                    isnull(sum(case DetailType
                                 when 206 then CostTotal
                                 else 0
                               end), 0) as Total206 ,
                    isnull(sum(case DetailType
                                 when 206 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal206 ,
                    isnull(sum(case DetailType
                                 when 207 then Qty
                                 else 0
                               end), 0) as Qty207 ,
                    isnull(sum(case DetailType
                                 when 207 then CostTotal
                                 else 0
                               end), 0) as Total207 ,
                    isnull(sum(case DetailType
                                 when 207 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal207 ,
                    isnull(sum(case DetailType
                                 when 208 then Qty
                                 else 0
                               end), 0) as Qty208 ,
                    isnull(sum(case DetailType
                                 when 208 then CostTotal
                                 else 0
                               end), 0) as Total208 ,
                    isnull(sum(case DetailType
                                 when 208 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal208 ,
                    isnull(sum(case DetailType
                                 when 209 then Qty
                                 else 0
                               end), 0) as Qty209 ,
                    isnull(sum(case DetailType
                                 when 209 then CostTotal
                                 else 0
                               end), 0) as Total209 ,
                    isnull(sum(case DetailType
                                 when 209 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal209 ,
                    isnull(sum(case DetailType
                                 when 210 then Qty
                                 else 0
                               end), 0) as Qty210 ,
                    isnull(sum(case DetailType
                                 when 210 then CostTotal
                                 else 0
                               end), 0) as Total210 ,
                    isnull(sum(case DetailType
                                 when 210 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal210 ,
                    isnull(sum(case DetailType
                                 when 212 then Qty
                                 else 0
                               end), 0) as Qty212 ,
                    isnull(sum(case DetailType
                                 when 212 then CostTotal
                                 else 0
                               end), 0) as Total212 ,
                    isnull(sum(case DetailType
                                 when 212 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal212 ,
                    isnull(sum(case DetailType
                                 when 213 then Qty
                                 else 0
                               end), 0) as Qty213 ,
                    isnull(sum(case DetailType
                                 when 213 then CostTotal
                                 else 0
                               end), 0) as Total213 ,
                    isnull(sum(case DetailType
                                 when 213 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal213 ,
                    isnull(sum(case DetailType
                                 when 214 then Qty
                                 else 0
                               end), 0) as Qty214 ,
                    isnull(sum(case DetailType
                                 when 214 then CostTotal
                                 else 0
                               end), 0) as Total214 ,
                    isnull(sum(case DetailType
                                 when 214 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal214 ,
                    isnull(sum(case DetailType
                                 when 215 then Qty
                                 else 0
                               end), 0) as Qty215 ,
                    isnull(sum(case DetailType
                                 when 215 then CostTotal
                                 else 0
                               end), 0) as Total215 ,
                    isnull(sum(case DetailType
                                 when 215 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal215 ,
                    isnull(sum(case DetailType
                                 when 216 then Qty
                                 else 0
                               end), 0) as Qty216 ,
                    isnull(sum(case DetailType
                                 when 216 then CostTotal
                                 else 0
                               end), 0) as Total216 ,
                    isnull(sum(case DetailType
                                 when 216 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal216 ,
                    isnull(sum(case DetailType
                                 when 218 then Qty
                                 else 0
                               end), 0) as Qty218 ,
                    isnull(sum(case DetailType
                                 when 218 then CostTotal
                                 else 0
                               end), 0) as Total218 ,
                    isnull(sum(case DetailType
                                 when 218 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal218 ,
                    isnull(sum(case DetailType
                                 when 220 then Qty
                                 else 0
                               end), 0) as Qty220 ,
                    isnull(sum(case DetailType
                                 when 220 then CostTotal
                                 else 0
                               end), 0) as Total220 ,
                    isnull(sum(case DetailType
                                 when 220 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal220 ,
                    isnull(sum(case DetailType
                                 when 221 then Qty
                                 else 0
                               end), 0) as Qty221 ,
                    isnull(sum(case DetailType
                                 when 221 then CostTotal
                                 else 0
                               end), 0) as Total221 ,
                    isnull(sum(case DetailType
                                 when 221 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal221 ,
                    isnull(sum(case DetailType
                                 when 301 then Qty
                                 else 0
                               end), 0) as Qty301 ,
                    isnull(sum(case DetailType
                                 when 301 then CostTotal
                                 else 0
                               end), 0) as Total301 ,
                    isnull(sum(case DetailType
                                 when 301 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal301 ,
                    isnull(sum(case DetailType
                                 when 401 then Qty
                                 else 0
                               end), 0) as Qty401 ,
                    isnull(sum(case DetailType
                                 when 401 then CostTotal
                                 else 0
                               end), 0) as Total401 ,
                    isnull(sum(case DetailType
                                 when 401 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal401
            from    #TempAllJXC2 a --where not (DetailType = 301 and (qty = 0 or CostTotal = 0)) 
            group by PtypeId
	end                    
			
	if @Displaymode = 2 
	begin	        
				
			select PtypeId,case when (detailtype > 200 and detailtype < 300) then -SUM(Qty) else SUM(Qty) end as qty,
					case when (detailtype > 200 and detailtype < 300) then -SUM(CostTotal) else SUM(CostTotal) end as costtotal,	detailtype,ColorId,SizeId,
						CASE WHEN (detailtype > 200 and detailtype < 300) THEN -sum(RetailTotal) ELSE sum(RetailTotal) END as RetailTotal into #TempAllJXC3 from 
				(			select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,DetailType,ColorId,SizeId,ROUND(CONVERT(NUMERIC(24,10),sum(c.RetailPrice*qty)),@dig_total) as retailtotal from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				where Datadate between @DateBegin and @DateEnd
				and exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId,ColorId,SizeId,DetailType
				union all
				select PtypeId,-SUM(Qty) as qty,-SUM(CostTotal) as costtotal,	401,ColorId,SizeId,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),-Qty)*CONVERT(NUMERIC(24,10),c.RetailPrice))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				where Datadate > @DateEnd
				and 
				exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId,ColorId,SizeId,DetailType
				union all
				select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	301,ColorId,SizeId,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				where Datadate < @DateBegin
				and 
				exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId,ColorId,SizeId
				union all (select Ptypeid,SUM(d.qty) as qty,SUM(d.total) as costtotal,301 as detialtype,d.ColorId,d.SizeId,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),d.Qty))),@dig_total) as retailtotal from IniGoodsStocks a inner join IniGoodsDetail d on a.OrderId = d.OrderId
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
						where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId,ColorId,SizeId)
				union all (select Ptypeid,SUM(d.qty) as qty,SUM(d.total) as costtotal,401 as detialtype,d.ColorId,d.SizeId,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),d.Qty))),@dig_total) as retailtotal from GoodsStocks a inner join Goodsstockdetail d on a.OrderId = d.OrderId
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
						where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId,ColorId,SizeId)							
				) a
				group by PtypeId,DetailType,colorid,sizeid
				
				
            select  PtypeId ,
                    Right('00000' + cast(colorid as varchar),5) as pctypeid ,
                    Right('00000' + cast(sizeid as varchar),5) as pstypeid ,
		    --(SELECT TOP 1 [Order] FROM [dbo].[Size] si WHERE right('00000' + CAST(si.SizeId as VARCHAR), 5)  = pstypeid ) AS psOrder , 
                    isnull(sum(case DetailType
                                 when 101 then Qty
                                 else 0
                               end), 0) as Qty101 ,
                    isnull(sum(case DetailType
                                 when 101 then CostTotal
                                 else 0
                               end), 0) as Total101 ,
                    isnull(sum(case DetailType
                                 when 101 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal101 ,
                    isnull(sum(case DetailType
                                 when 102 then Qty
                                 else 0
                               end), 0) as Qty102 ,
                    isnull(sum(case DetailType
                                 when 102 then CostTotal
                                 else 0
                               end), 0) as Total102 ,
                    isnull(sum(case DetailType
                                 when 102 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal102 ,
                    isnull(sum(case DetailType
                                 when 103 then Qty
                                 else 0
                               end), 0) as Qty103 ,
                    isnull(sum(case DetailType
                                 when 103 then CostTotal
                                 else 0
                               end), 0) as Total103 ,
                    isnull(sum(case DetailType
                                 when 103 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal103 ,
                    isnull(sum(case DetailType
                                 when 104 then Qty
                                 else 0
                               end), 0) as Qty104 ,
                    isnull(sum(case DetailType
                                 when 104 then CostTotal
                                 else 0
                               end), 0) as Total104 ,
                    isnull(sum(case DetailType
                                 when 104 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal104 ,
                    isnull(sum(case DetailType
                                 when 105 then Qty
                                 else 0
                               end), 0) as Qty105 ,
                    isnull(sum(case DetailType
                                 when 105 then CostTotal
                                 else 0
                               end), 0) as Total105 ,
                    isnull(sum(case DetailType
                                 when 105 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal105 ,
                    isnull(sum(case DetailType
                                 when 106 then Qty
                                 else 0
                               end), 0) as Qty106 ,
                    isnull(sum(case DetailType
                                 when 106 then CostTotal
                                 else 0
                               end), 0) as Total106 ,
                    isnull(sum(case DetailType
                                 when 106 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal106 ,
                    isnull(sum(case DetailType
                                 when 107 then Qty
                                 else 0
                               end), 0) as Qty107 ,
                    isnull(sum(case DetailType
                                 when 107 then CostTotal
                                 else 0
                               end), 0) as Total107 ,
                    isnull(sum(case DetailType
                                 when 107 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal107 ,
                    isnull(sum(case DetailType
                                 when 108 then Qty
                                 else 0
                               end), 0) as Qty108 ,
                    isnull(sum(case DetailType
                                 when 108 then CostTotal
                                 else 0
                               end), 0) as Total108 ,
                    isnull(sum(case DetailType
                                 when 108 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal108 ,
                    isnull(sum(case DetailType
                                 when 109 then Qty
                                 else 0
                               end), 0) as Qty109 ,
                    isnull(sum(case DetailType
                                 when 109 then CostTotal
                                 else 0
                               end), 0) as Total109 ,
                    isnull(sum(case DetailType
                                 when 109 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal109 ,
                    isnull(sum(case DetailType
                                 when 110 then Qty
                                 else 0
                               end), 0) as Qty110 ,
                    isnull(sum(case DetailType
                                 when 110 then CostTotal
                                 else 0
                               end), 0) as Total110 ,
                    isnull(sum(case DetailType
                                 when 110 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal110 ,
                    isnull(sum(case DetailType
                                 when 112 then Qty
                                 else 0
                               end), 0) as Qty112 ,
                    isnull(sum(case DetailType
                                 when 112 then CostTotal
                                 else 0
                               end), 0) as Total112 ,
                    isnull(sum(case DetailType
                                 when 112 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal112 ,
                    isnull(sum(case DetailType
                                 when 113 then Qty
                                 else 0
                               end), 0) as Qty113 ,
                    isnull(sum(case DetailType
                                 when 113 then CostTotal
                                 else 0
                               end), 0) as Total113 ,
                    isnull(sum(case DetailType
                                 when 113 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal113 ,
                    isnull(sum(case DetailType
                                 when 114 then Qty
                                 else 0
                               end), 0) as Qty114 ,
                    isnull(sum(case DetailType
                                 when 114 then CostTotal
                                 else 0
                               end), 0) as Total114 ,
                    isnull(sum(case DetailType
                                 when 114 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal114 ,
                    isnull(sum(case DetailType
                                 when 115 then Qty
                                 else 0
                               end), 0) as Qty115 ,
                    isnull(sum(case DetailType
                                 when 115 then CostTotal
                                 else 0
                               end), 0) as Total115 ,
                    isnull(sum(case DetailType
                                 when 115 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal115 ,
                    isnull(sum(case DetailType
                                 when 116 then Qty
                                 else 0
                               end), 0) as Qty116 ,
                    isnull(sum(case DetailType
                                 when 116 then CostTotal
                                 else 0
                               end), 0) as Total116 ,
                    isnull(sum(case DetailType
                                 when 116 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal116 ,
                    isnull(sum(case DetailType
                                 when 118 then Qty
                                 else 0
                               end), 0) as Qty118 ,
                    isnull(sum(case DetailType
                                 when 118 then CostTotal
                                 else 0
                               end), 0) as Total118 ,
                    isnull(sum(case DetailType
                                 when 118 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal118 ,
                    isnull(sum(case DetailType
                                 when 120 then Qty
                                 else 0
                               end), 0) as Qty120 ,
                    isnull(sum(case DetailType
                                 when 120 then CostTotal
                                 else 0
                               end), 0) as Total120 ,
                    isnull(sum(case DetailType
                                 when 120 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal120 ,
                    isnull(sum(case DetailType
                                 when 121 then Qty
                                 else 0
                               end), 0) as Qty121 ,
                    isnull(sum(case DetailType
                                 when 121 then CostTotal
                                 else 0
                               end), 0) as Total121 ,
                    isnull(sum(case DetailType
                                 when 121 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal121 ,
                    isnull(sum(case DetailType
                                 when 201 then Qty
                                 else 0
                               end), 0) as Qty201 ,
                    isnull(sum(case DetailType
                                 when 201 then CostTotal
                                 else 0
                               end), 0) as Total201 ,
                    isnull(sum(case DetailType
                                 when 201 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal201 ,
                    isnull(sum(case DetailType
                                 when 202 then Qty
                                 else 0
                               end), 0) as Qty202 ,
                    isnull(sum(case DetailType
                                 when 202 then CostTotal
                                 else 0
                               end), 0) as Total202 ,
                    isnull(sum(case DetailType
                                 when 202 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal202 ,
                    isnull(sum(case DetailType
                                 when 203 then Qty
                                 else 0
                               end), 0) as Qty203 ,
                    isnull(sum(case DetailType
                                 when 203 then CostTotal
                                 else 0
                               end), 0) as Total203 ,
                    isnull(sum(case DetailType
                                 when 203 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal203 ,
                    isnull(sum(case DetailType
                                 when 204 then Qty
                                 else 0
                               end), 0) as Qty204 ,
                    isnull(sum(case DetailType
                                 when 204 then CostTotal
                                 else 0
                               end), 0) as Total204 ,
                    isnull(sum(case DetailType
                                 when 204 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal204 ,
                    isnull(sum(case DetailType
                                 when 205 then Qty
                                 else 0
                               end), 0) as Qty205 ,
                    isnull(sum(case DetailType
                                 when 205 then CostTotal
                                 else 0
                               end), 0) as Total205 ,
                    isnull(sum(case DetailType
                                 when 205 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal205 ,
                    isnull(sum(case DetailType
                                 when 206 then Qty
                                 else 0
                               end), 0) as Qty206 ,
                    isnull(sum(case DetailType
                                 when 206 then CostTotal
                                 else 0
                               end), 0) as Total206 ,
                    isnull(sum(case DetailType
                                 when 206 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal206 ,
                    isnull(sum(case DetailType
                                 when 207 then Qty
                                 else 0
                               end), 0) as Qty207 ,
                    isnull(sum(case DetailType
                                 when 207 then CostTotal
                                 else 0
                               end), 0) as Total207 ,
                    isnull(sum(case DetailType
                                 when 207 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal207 ,
                    isnull(sum(case DetailType
                                 when 208 then Qty
                                 else 0
                               end), 0) as Qty208 ,
                    isnull(sum(case DetailType
                                 when 208 then CostTotal
                                 else 0
                               end), 0) as Total208 ,
                    isnull(sum(case DetailType
                                 when 208 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal208 ,
                    isnull(sum(case DetailType
                                 when 209 then Qty
                                 else 0
                               end), 0) as Qty209 ,
                    isnull(sum(case DetailType
                                 when 209 then CostTotal
                                 else 0
                               end), 0) as Total209 ,
                    isnull(sum(case DetailType
                                 when 209 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal209 ,
                    isnull(sum(case DetailType
                                 when 210 then Qty
                                 else 0
                               end), 0) as Qty210 ,
                    isnull(sum(case DetailType
                                 when 210 then CostTotal
                                 else 0
                               end), 0) as Total210 ,
                    isnull(sum(case DetailType
                                 when 210 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal210 ,
                    isnull(sum(case DetailType
                                 when 212 then Qty
                                 else 0
                               end), 0) as Qty212 ,
                    isnull(sum(case DetailType
                                 when 212 then CostTotal
                                 else 0
                               end), 0) as Total212 ,
                    isnull(sum(case DetailType
                                 when 212 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal212 ,
                    isnull(sum(case DetailType
                                 when 213 then Qty
                                 else 0
                               end), 0) as Qty213 ,
                    isnull(sum(case DetailType
                                 when 213 then CostTotal
                                 else 0
                               end), 0) as Total213 ,
                    isnull(sum(case DetailType
                                 when 213 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal213 ,
                    isnull(sum(case DetailType
                                 when 214 then Qty
                                 else 0
                               end), 0) as Qty214 ,
                    isnull(sum(case DetailType
                                 when 214 then CostTotal
                                 else 0
                               end), 0) as Total214 ,
                    isnull(sum(case DetailType
                                 when 214 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal214 ,
                    isnull(sum(case DetailType
                                 when 215 then Qty
                                 else 0
                               end), 0) as Qty215 ,
                    isnull(sum(case DetailType
                                 when 215 then CostTotal
                                 else 0
                               end), 0) as Total215 ,
                    isnull(sum(case DetailType
                                 when 215 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal215 ,
                    isnull(sum(case DetailType
                                 when 216 then Qty
                                 else 0
                               end), 0) as Qty216 ,
                    isnull(sum(case DetailType
                                 when 216 then CostTotal
                                 else 0
                               end), 0) as Total216 ,
                    isnull(sum(case DetailType
                                 when 216 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal216 ,
                    isnull(sum(case DetailType
                                 when 218 then Qty
                                 else 0
                               end), 0) as Qty218 ,
                    isnull(sum(case DetailType
                                 when 218 then CostTotal
                                 else 0
                               end), 0) as Total218 ,
                    isnull(sum(case DetailType
                                 when 218 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal218 ,
                    isnull(sum(case DetailType
                                 when 220 then Qty
                                 else 0
                               end), 0) as Qty220 ,
                    isnull(sum(case DetailType
                                 when 220 then CostTotal
                                 else 0
                               end), 0) as Total220 ,
                    isnull(sum(case DetailType
                                 when 220 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal220 ,
                    isnull(sum(case DetailType
                                 when 221 then Qty
                                 else 0
                               end), 0) as Qty221 ,
                    isnull(sum(case DetailType
                                 when 221 then CostTotal
                                 else 0
                               end), 0) as Total221 ,
                    isnull(sum(case DetailType
                                 when 221 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal221 ,
                    isnull(sum(case DetailType
                                 when 301 then Qty
                                 else 0
                               end), 0) as Qty301 ,
                    isnull(sum(case DetailType
                                 when 301 then CostTotal
                                 else 0
                               end), 0) as Total301 ,
                    isnull(sum(case DetailType
                                 when 301 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal301 ,
                    isnull(sum(case DetailType
                                 when 401 then Qty
                                 else 0
                               end), 0) as Qty401 ,
                    isnull(sum(case DetailType
                                 when 401 then CostTotal
                                 else 0
                               end), 0) as Total401 ,
                    isnull(sum(case DetailType
                                 when 401 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal401
            from    #TempAllJXC3 a --where not (DetailType = 301 and (qty = 0 or CostTotal = 0)) 
		
            group by PtypeId ,
                    ColorId ,
                    SizeId	
	end                    
    if object_id('tempdb..#AllJXCKtypeIdTable') is not null 
        drop table #AllJXCKtypeIdTable
    if object_id('tempdb..#AllJXCPtypeIdTable') is not null 
        drop table #AllJXCPtypeIdTable        
    if object_id('tempdb..#TempAllJXC1') is not null 
        drop table #TempAllJXC1       
    if object_id('tempdb..#TempAllJXC2') is not null 
        drop table #TempAllJXC2       
    if object_id('tempdb..#TempAllJXC2q') is not null 
        drop table #TempAllJXC2q                      
    if object_id('tempdb..#TempAllJXC3') is not null 
        drop table #TempAllJXC3                               
        
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_FZGetBtypeBalance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FN_FZGetBtypeBalance]
GO




--在按单结算中单位的按单结算信息
--  ********************************************************************************************
--  ||                                                                                        
--  ||   过程名称：F_D_GetBtypeBalance                                     
--  ||   过程功能：按单结算
--  ||=========================================================================================
--  ||   参数说明：  参数名称         类型            意义                     输入输出
--  ||            -----------------------------------------------------------------------------
--  ||                       @BTypeID VARCHAR(50),  往来单位id
--  ||            	  @StartDate VARCHAR(10), 开始日期
--  ||          	  @EndDate VARCHAR(10), 结束日期
--  ||                       @VchType INT,                   VchType = 4  -- 收款单，66--付款单, 253--往来核销单
--  ||                       @CurBillNumerID int    当前单据的单据号
--  ||=========================================================================================   
--  ||   返回值：         值                                     说明
--  ||       ----------------------------------------------------------------------------------------
--  ||                    0                                 执行成功
--  ||                  －1                               执行失败
--  ||==========================================================================================
CREATE       PROCEDURE FN_FZGetBtypeBalance
(
	@BranchId	varchar(50),
	@BtypeId        varchar(50),
  	@StartDate      VARCHAR(10),--格式2012-06-05
	@EndDate        VARCHAR(10),--格式2012-06-05
	@VchType        int,
	@BanlanceVchType int,
        @CurBillNumerID bigint= 0,
        @ShopID         varchar(50) = ''
)
AS
  	SET NOCOUNT ON
	Select @BTypeID = LTRIM(RTRIM(@BTypeID)), @StartDate = LTRIM(RTRIM(@StartDate)), @EndDate = LTRIM(RTRIM(@EndDate))
	Select @ShopID = isnull(@ShopID,'') + '%' 
	
	declare @dt_startDate varchar(10),@dt_endDate varchar(10)
	
	if @StartDate<>'' and @EndDate<>''
		select @dt_startDate=@StartDate,@dt_endDate=@EndDate
	else 
		select @dt_startDate='1900-01-01',@dt_endDate='2100-01-01'
	
	---------------------------
	
	IF OBJECT_ID('tempdb..#BillData')IS NOT NULL DROP TABLE #BillData
	SELECT	d.bFullName ,
		d.btypeid ,
		d.VchName ,
		d.summary ,
		d.VchType ,
		d.Vchcode ,
		d.DlyVchcode ,
		d.[Date] ,
		d.Number ,
		d.Total AS VchTotal ,
		SUM(ISNULL(ABS(g.GatheringTotal), 0)) AS GatheringTotal ,
		d.Total
		- CASE WHEN d.total > 0
					AND d.vchtype NOT IN ( 12, 24 )
			   THEN SUM(ISNULL(ABS(g.GatheringTotal), 0))
			   WHEN d.total = 0
					AND d.vchtype = 34
			   THEN SUM(ISNULL(( -g.GatheringTotal ), 0))
			   WHEN d.vchtype = 24
					AND d.total < 0
			   THEN CASE WHEN SUM(ISNULL(-g.GatheringTotal, 0)) > 0
						 THEN -ABS(SUM(ISNULL(-g.GatheringTotal, 0)))
						 ELSE ABS(SUM(ISNULL(-g.GatheringTotal, 0)))
					END    --修改为先求绝对值，再加负号，对应Mantis问题编号0026940   
			   WHEN d.vchtype = 12 THEN SUM(ISNULL(( g.GatheringTotal ), 0))
			   WHEN d.vchtype = 253
					AND d.total < 0 THEN SUM(ISNULL(( -g.GatheringTotal ), 0))
			   ELSE SUM(ISNULL(g.GatheringTotal, 0))
		  END AS BalanceTotal ,       
		d.etypeid ,
		d.curktypeid AS ktypeid ,
		d.curbranchid AS branchid ,
		d.account INTO #BillData 
	 FROM	( SELECT	d.* ,
						CASE WHEN d.vchtype IN ( 222, 234 ) THEN d.branchid2
							 WHEN d.branchid3 <> '' THEN d.branchid3
							 ELSE d.branchid
						END AS curbranchid ,
						CASE WHEN d.vchtype IN ( 222, 234 ) THEN d.ktypeid2
							 ELSE d.ktypeid
						END AS curktypeid
			  FROM		dbo.view_zz_Dlyndx d
			) d
			LEFT OUTER JOIN ( SELECT	
										g.VchCode ,
										CASE WHEN d.vchtype = 24
												  AND g.[type] = 2 THEN -g.Total
											 ELSE g.Total
										END GatheringTotal 
							  FROM		dbo.DlyNdx d
										  INNER JOIN GatheringDly g ON d.VchCode = g.GatheringVchCode
							  WHERE		d.RedOld = 'F'
										AND g.draft = 2
							) g ON d.Vchcode = g.VchCode
	 WHERE	( d.VchType IN ( 11, 12, 13, 34, 6, 300, 301, 45, 26, 28, 24, 222, 224,
							 232, 234, 250 ) )
			AND ( d.draft = 2 )
			AND ( d.redold = 'F' )
			AND d.curbranchid =@BranchId 
		    And d.BTypeID = @BTypeID 
		    AND d.[date] between @dt_startDate and @dt_endDate 
	 GROUP BY d.bFullName ,
			d.btypeid ,
			d.VchName ,
			d.summary ,
			d.curktypeid ,
			d.VchType ,
			d.Vchcode ,
			d.DlyVchcode ,
			d.[Date] ,
			d.Number ,
			d.Total ,
			d.etypeid ,
			d.curbranchid ,
			d.account         
     
	---------------------------	
		

	If @VchType = 4  -- 收款单
	Begin
		Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number,
			 CASE WHEN b.vchtype IN (24,12,253) THEN VchTotal ELSE abs(VchTotal) END as VchTotal, GatheringTotal, 
			 CASE WHEN b.vchtype IN (24,12,253) THEN BalanceTotal ELSE abs(BalanceTotal) END as BalanceTotal, ETypeID,
			 (SELECT CASE WHEN  b.vchtype IN (24,12,253) THEN Sum(total) ELSE Sum(abs(total))  END 
			 from gatheringdly a where a.vchcode= b.vchcode and a.gatheringvchcode = @CurBillNumerID and draft = 2) Curbalance --当前结算单结算的金额
		From #billdata b
		Where  (((b.ktypeid in (Select typeid from stock where branchid like @ShopID+'%') 
        		And (b.vchtype IN (11,26,222,234) 
        		or b.vchtype in (24,12))  OR (b.VchType=253 AND EXISTS(SELECT 1 FROM dbo.DlyNdx WHERE b.Vchcode=Vchcode AND PHID=10    )) )
        			--应收冲应收 转入单位可能产生应付（负金额）
			And (case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end > 0
			 or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2))
       			And b.vchcode not in (select draftBillcode from Posretailbill))) 
		
       	UNION
       	Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number, -abs(VchTotal) as VchTotal, GatheringTotal, -abs(BalanceTotal) as BalanceTotal, ETypeID,
			(select -Sum(abs(total)) from gatheringdly a where a.vchcode= b.vchcode 
			and a.gatheringvchcode = @CurBillNumerID and draft = 2) Curbalance --当前结算单结算的金额
		From #billdata b
		Where  ((b.ktypeid in (Select typeid from stock where branchid like @ShopID+'%') 
        	And b.vchtype in (45,224)
			And (case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end > 0
			 or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2))
       			And b.vchcode not in (select draftBillcode from Posretailbill))) 
			
		Union
		--无收款单或有收款单为草稿，取期初
		Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
		From (
			Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应收款' as Summary, 
				-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
				'QCYS' as Number, isnull(bb.ARTotal00,0) as VchTotal,0 as GatheringTotal,
	    			(isnull(bb.ARTotal00,0) - isnull((
					Select sum(isnull(Total,0)) From GatheringDly 
					Where Btypeid = @BTypeID and vchCode = -1 and Type IN (1,3,5) and draft<>1 
						--And GatheringVchCode In (Select VchCode From DlyNdx where VchType IN (4,253) and redold = 'F')
						and exists(select 1 from dlyndx n where (n.vchtype=4 or n.vchtype=253) 
						and redold='F' and n.branchid=@BranchId and n.vchcode=GatheringVchCode)
					),0)) as balancetotal,
				'00000' as ETypeID,0 as Curbalance 
			From btype b,BranchBtype bb 
			Where b.typeid = @Btypeid And b.typeid=bb.btypeid and bb.branchid=@BranchId 
			) t	
		Where balancetotal <> 0 and (@CurBillNumerID=0 Or 
			Exists(Select 1 From DlyNdx Where VchCode=@CurBillNumerID And VchType IN (4,253) And Draft=1))
		Union
		--有收款单号且已过帐收款单，取期初
		Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
		From (
			Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应收款' as Summary, 
				-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) 
				From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
				'QCYS' as Number, isnull(bb.ARTotal00,0) as VchTotal,0 as GatheringTotal,
	    			(isnull(bb.ARTotal00,0) - isnull((
					Select sum(isnull(Total,0)) From GatheringDly 
					Where Btypeid = @BTypeID and vchCode = -1 and Type IN (1,3,5) and draft<>1 
						and exists(select 1 from dlyndx n where (n.vchtype=4 or n.vchtype=253)
						 and redold='F' and n.branchid=@BranchId and n.vchcode<>@CurBillNumerID and n.vchcode=GatheringVchCode)
					),0)) as balancetotal,
				'00000' as ETypeID,0 as Curbalance 
			From GatheringDly g,btype b ,BranchBtype bb
			Where gatheringvchcode = @CurBillNumerID And vchcode=-1 and b.typeid=g.btypeid 
				And b.typeid=bb.btypeid and bb.branchid=@BranchId
				And Exists(Select 1 From DlyNdx Where VchCode=@CurBillNumerID And VchType IN (4,253) And Draft=2)
			) t1
		
     		ORDER BY b.VchCode
	End
	ELSE IF @VchType = 66
	Begin
    		Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number, 
			case when b.VchType=253 then VchTotal else abs(VchTotal) end as VchTotal, GatheringTotal, 
			case when b.VchType=253 then BalanceTotal else abs(BalanceTotal) end as BalanceTotal, ETypeID,
			(Select case when b.VchType=253 then sum(total) else Sum(abs(total)) end 
			from gatheringdly a where a.vchcode= b.vchcode and a.gatheringvchcode = @CurBillNumerID) Curbalance
		FROM #billdata b
		Where ((
		     	((b.vchtype in (28,34,13,232) --(28,34,45,13,224,232)
				) OR (b.VchType=253 AND EXISTS(SELECT 1 FROM dbo.DlyNdx WHERE b.Vchcode=Vchcode AND PHID=11   )))
				--应付冲应付 转入单位可能产生应收（负金额）
			and (case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end  > 0 
			or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2)))) 
			
		UNION
			Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number, -abs(VchTotal) as VchTotal, GatheringTotal, -abs(BalanceTotal) as BalanceTotal, ETypeID,
			(Select -Sum(abs(total)) from gatheringdly a where a.vchcode= b.vchcode and a.gatheringvchcode = @CurBillNumerID) Curbalance
		FROM #billdata b
		Where ((b.vchtype in (6,234) 
			and (case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end  > 0 
			or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2))))
		
		Union
		--无付款单或有付款单为草稿，取期初
		Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
		From (
			Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应付款' as Summary, 
				-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
				'QCYF' as Number,isnull(bb.APTotal00,0) as VchTotal,0 as GatheringTotal,
				(isnull(bb.APTotal00,0) - isnull((
					Select sum(isnull( Total,0)) From GatheringDly 
					where Btypeid = @BTypeID and vchCode = -1 and Type IN (2,4,6) and  draft<>1 
						and exists(select 1 from dlyndx n where (n.vchtype=66 or n.vchtype=253) 
						and redold='F' and n.branchid=@BranchId and n.vchcode=GatheringVchCode)
					),0)) as balancetotal,
				'00000' as ETypeID,0 as Curbalance 
			From btype b,BranchBtype bb 
			Where b.typeid = @Btypeid And b.typeid=bb.btypeid and bb.branchid=@BranchId 
			) t
		Where balancetotal <> 0 And (@CurBillNumerID=0 
		Or Exists(Select 1 From DlyNdx Where VchCode=@CurBillNumerID And VchType IN (66,253) And Draft=1))
		Union
		--有付款单号且已过帐付款单，取期初
		Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
			Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
		From (
			Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应付款' as Summary, 
				-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
				'QCYF' as Number,isnull(bb.APTotal00,0) as VchTotal,0 as GatheringTotal,
				(isnull(bb.APTotal00,0) - isnull((
					Select sum(isnull(- Total,0)) From GatheringDly 
					where Btypeid = @BTypeID and vchCode = -1 and Type IN (2,4,6) and  draft<>1 
						--And GatheringVchCode In (Select VchCode From DlyNdx where VchType IN (66,253) and redold = 'F' And VchCode<>@CurBillNumerID)
						and exists(select 1 from dlyndx n where (n.vchtype=66 or n.vchtype=253) 
						and redold='F' and n.branchid=@BranchId And n.VchCode<>@CurBillNumerID and n.vchcode=GatheringVchCode)
					),0)) as balancetotal,
				'00000' as ETypeID,0 as Curbalance 
			From GatheringDly g, btype b,BranchBtype bb 
			Where gatheringvchcode = @CurBillNumerID And vchcode=-1 and b.typeid=g.btypeid And b.typeid=bb.btypeid and bb.branchid=@BranchId 
				And Exists(Select 1 From DlyNdx Where VchCode=@CurBillNumerID And VchType IN (66,253) And Draft=2)
			) t1
		Order by b.VchCode
	End
	else if @vchtype=253
	begin
		If @BanlanceVchType = 4  -- 收款单
		Begin
			Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number,
				 CASE WHEN b.vchtype IN (24,12,253) THEN VchTotal ELSE abs(VchTotal) END as VchTotal, GatheringTotal, 
				 CASE WHEN b.vchtype IN (24,12,253) THEN BalanceTotal ELSE abs(BalanceTotal) END as BalanceTotal, ETypeID,
				 (SELECT CASE WHEN  b.vchtype IN (24,12,253) THEN Sum(total) ELSE Sum(abs(total))  END 
				 from gatheringdly a where a.vchcode= b.vchcode 
				 and a.gatheringvchcode = @CurBillNumerID and draft = 2) Curbalance --当前结算单结算的金额
			From #billdata b
			Where (((b.ktypeid in (Select typeid from stock where branchid like @ShopID+'%') 
        			And (b.vchtype IN (11,26,234) 
					or (b.vchtype = 222 and exists (select 1 from dlyndx where vchcode=b.DlyVchcode and draft=2 ))--加盟商配货单需要验收
        			or b.vchtype in (24,12))  OR (b.VchType=253 AND EXISTS(SELECT 1 FROM dbo.DlyNdx WHERE b.Vchcode=Vchcode AND PHID=10  )) )
        			--应收冲应收 转入单位可能产生应付（负金额）
				And (case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end > 0 
				or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2))
       				And b.vchcode not in (select draftBillcode from Posretailbill))) 
			
       		UNION
       		Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number, -abs(VchTotal) as VchTotal, GatheringTotal, -abs(BalanceTotal) as BalanceTotal, ETypeID,
				(select -Sum(abs(total)) from gatheringdly a where a.vchcode= b.vchcode 
				     and a.gatheringvchcode = @CurBillNumerID and draft = 2) Curbalance --当前结算单结算的金额
			From #billdata b
			Where ((b.ktypeid in (Select typeid from stock where branchid like @ShopID+'%') 
        		And b.vchtype in (45,224)
				And (case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end > 0
				 or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2))
       				And b.vchcode not in (select draftBillcode from Posretailbill))) 
			Union
			--无收款单或有收款单为草稿，取期初
			Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
			From (
				Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应收款' as Summary, 
					-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
					'QCYS' as Number, isnull(bb.ARTotal00,0) as VchTotal,0 as GatheringTotal,
	    				(isnull(bb.ARTotal00,0) - isnull((
						Select sum(isnull(Total,0)) From GatheringDly 
						Where Btypeid = @BTypeID and vchCode = -1 and Type IN (1,3,5) and draft<>1 
							--And GatheringVchCode In (Select VchCode From DlyNdx where VchType IN (4,253) and redold = 'F')
							and exists(select 1 from dlyndx n where (n.vchtype=4 or n.vchtype=253) 
							and redold='F' and n.branchid=@BranchId and n.vchcode=GatheringVchCode)
						),0)) as balancetotal,
					'00000' as ETypeID,0 as Curbalance 
				From btype b,BranchBtype bb 
				Where b.typeid = @Btypeid And b.typeid=bb.btypeid and bb.branchid=@BranchId 
				) t	
			Where balancetotal <> 0 and (@CurBillNumerID=0 
			Or Exists(Select 1 From DlyNdx Where VchCode=@CurBillNumerID And VchType IN (4,253) And Draft=1))
			Union
			--有收款单号且已过帐收款单，取期初
			Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
			From (
				Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应收款' as Summary, 
					-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
					'QCYS' as Number, isnull(bb.ARTotal00,0) as VchTotal,0 as GatheringTotal,
	    				(isnull(bb.ARTotal00,0) - isnull((
						Select sum(isnull(Total,0)) From GatheringDly 
						Where Btypeid = @BTypeID and vchCode = -1 and Type IN (1,3,5) and draft<>1 
							and exists(select 1 from dlyndx n where (n.vchtype=4 or n.vchtype=253) 
							and redold='F' and n.branchid=@BranchId  And n.VchCode<>@CurBillNumerID and n.vchcode=GatheringVchCode)
						),0)) as balancetotal,
					'00000' as ETypeID,0 as Curbalance 
				From GatheringDly g,btype b ,BranchBtype bb
				Where gatheringvchcode = @CurBillNumerID And vchcode=-1 and b.typeid=g.btypeid And b.typeid=bb.btypeid and bb.branchid=@BranchId
					And Exists(Select 1 From DlyNdx Where VchCode=@CurBillNumerID And VchType IN (4,253) And Draft=2)
				) t1
			
     			ORDER BY b.VchCode
		End
		ELSE IF @BanlanceVchType = 66
		Begin
    			Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number, 
				case when b.VchType=253 then VchTotal else abs(VchTotal) end as VchTotal, GatheringTotal, 
				case when b.VchType=253 then BalanceTotal else abs(BalanceTotal) end as BalanceTotal, ETypeID,
				(Select case when b.VchType=253 then sum(total) else Sum(abs(total)) end 
				from gatheringdly a where a.vchcode= b.vchcode and a.gatheringvchcode = @CurBillNumerID) Curbalance
			FROM #billdata b
			Where (
			    	(
		     		(
					(b.vchtype in (28,34,13))
					OR (b.vchtype=232 and exists(select 1 from dlyndx where  b.Vchcode=Vchcode and draft=2))
					OR (b.VchType=253 AND EXISTS(SELECT 1 FROM dbo.DlyNdx WHERE b.Vchcode=Vchcode AND PHID=11   ))
					)--应付冲应付 转入单位可能产生应收（负金额）
					and 
					(case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end  > 0
					 or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2))
				)
				) 
	
			UNION
				Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number, -abs(VchTotal) as VchTotal, GatheringTotal, -abs(BalanceTotal) as BalanceTotal, ETypeID,
				(Select -Sum(abs(total)) from gatheringdly a where a.vchcode= b.vchcode and a.gatheringvchcode = @CurBillNumerID) Curbalance
			FROM #billdata b
			Where  ((b.vchtype in (6,234) 
				and (case when b.VchTotal >= 0 then b.BalanceTotal else -b.BalanceTotal end  > 0 
				or b.VchCode in (select vchcode from GatheringDly where gatheringvchcode = @CurBillNumerID and draft = 2))))
		
			Union
			--无付款单或有付款单为草稿，取期初
			Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
			From (
				Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应付款' as Summary, 
					-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
					'QCYF' as Number,isnull(bb.APTotal00,0) as VchTotal,0 as GatheringTotal,
					(isnull(bb.APTotal00,0) - isnull((
						Select sum(isnull(Total,0)) From GatheringDly 
						where Btypeid = @BTypeID and vchCode = -1 and Type IN (2,4,6) and  draft<>1 
							--And GatheringVchCode In (Select VchCode From DlyNdx where VchType IN (66,253) and redold = 'F')
							and exists(select 1 from dlyndx n where (n.vchtype=66 or n.vchtype=253) 
							and redold='F' and n.branchid=@BranchId and n.vchcode=GatheringVchCode)
						),0)) as balancetotal,
					'00000' as ETypeID,0 as Curbalance 
				From btype b,BranchBtype bb 
				Where b.typeid = @Btypeid And b.typeid=bb.btypeid and bb.branchid=@BranchId 
				) t
			Where balancetotal <> 0 And (@CurBillNumerID=0 
			  Or Exists(Select 1 From DlyNdx	Where VchCode=@CurBillNumerID And VchType IN (66,253) And Draft=1))
			Union
			--有付款单号且已过帐付款单，取期初
			Select bFullName, BTypeID, VchName, Summary, VchType, VchCode, cast(Date as varchar(10)) as [date], 
				Number, VchTotal, GatheringTotal, BalanceTotal, ETypeID, Curbalance
			From (
				Select b.FullName as bFullName, b.TypeID  as Btypeid,'期初' as VchName,'期初应付款' as Summary, 
					-1 as VchType,-1 as VchCode,cast((Select Max(SubValue) From Sysdata where SubName = 'startdate') as varchar(10)) as [date],
					'QCYF' as Number,isnull(bb.APTotal00,0) as VchTotal,0 as GatheringTotal,
					(isnull(bb.APTotal00,0) - isnull((
						Select sum(isnull(- Total,0)) From GatheringDly 
						where Btypeid = @BTypeID and vchCode = -1 and Type IN (2,4,6) and  draft<>1 
							and exists(select 1 from dlyndx n where (n.vchtype=4 or n.vchtype=253) and redold='F' 
							and n.branchid=@BranchId  And n.VchCode<>@CurBillNumerID and n.vchcode=GatheringVchCode)
						),0)) as balancetotal,
					'00000' as ETypeID,0 as Curbalance 
				From GatheringDly g, btype b,BranchBtype bb 
				Where gatheringvchcode = @CurBillNumerID And vchcode=-1 and b.typeid=g.btypeid And b.typeid=bb.btypeid and bb.branchid=@BranchId 
					And Exists(Select 1 From DlyNdx Where VchCode=@CurBillNumerID And VchType IN (66,253) And Draft=2)
				) t1
			Order by b.VchCode
		End
	end
	Else If @VchType = 0
		Select b.*, (Select Sum(total) From gatheringdly a Where a.vchcode= b.vchcode and a.gatheringvchcode = @CurBillNumerID) Curbalance
		From #billdata b
		Where  (b.BalanceTotal <> 0 or b.VchCode in (select vchcode 
			from GatheringDly where gatheringvchcode = @CurBillNumerID and draft=2))
		   
		Order By b.VchCode
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




/*
	作者：cqh
	日期：2011-08-24
	描述：返回IP字符串
	实例：
			GetIPlist(2)
*/

CREATE  FUNCTION GetIPlist 
 ( 
    @etypeid varchar(100)
 ) 
returns varchar(1000)
--@ENCODE$--
AS 
BEGIN 
	DECLARE @returnstr varchar(2000)
	SET @returnstr =''
	
	
	select @returnstr=ipaddr FROM (SELECT ipaddr=
	  (select IpAddr+'~'+REVERSE(rtrim(ltrim(ipmax))+substring(REVERSE(IpAddr),charindex('.',REVERSE(IpAddr)),len(IpAddr)))+'    ' FROM LoginIP  where EtypeID =@etypeid
	  FOR XML PATH(''))
  FROM LoginIP 
  where EtypeID =@etypeid)x


	
	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].[FN_FZQueryBtypeSaleList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FN_FZQueryBtypeSaleList]
GO




--  ********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：QueryBtypeSaleList(列表)              
--  ||   过程功能：取得往来单位的销售、回款，和应收应付等统计信息  
--  ||=========================================================================================  
--  ||   参数说明：  参数名称         类型            意义                     输入输出  
--  ||            -----------------------------------------------------------------------------  
--  ||           @Btypeid              varchar(50),        职员Id  
--  ||           @Startdate             varchar(10),        开始时间  
--  ||           @Enddate               varchar(10),        结束时间  
--  ||=========================================================================================     
--  ||   返回值：         值                                     说明  
--  ||       ----------------------------------------------------------------------------------------  
--  ||               
--  ||==========================================================================================  
CREATE    PROCEDURE FN_FZQueryBtypeSaleList  

(
   @Btypeid     varchar(50),  
   @szStartDate varchar(10),  
   @szEndDate   varchar(10),
   @branchid	varchar(50),
   @OperatorId  varchar(50)    
)
AS  

DECLARE @str varchar(10)   
IF LEFT(@branchid ,5)='00001'  
begin  
   set @str='2,3,4'        
end  
ELSE  
begin  
   set @str='6'     
end

--Btype 表的权限
select TypeId into #btypeBtypeSaleList  FROM FN_GetPowerRangeBList(@OperatorId,@BtypeID,@str) 
        WHERE (@branchid = case @str when '6' then Left(branchid,Len(@branchid)) else @branchid end)  
  	or (branchid = case @str when '6' then Left(@branchid,Len(branchid)) else branchid end)   



--往来单位多级权限
IF(OBJECT_ID('tempdb..#BListTemp') IS NOT NULL)
	DROP TABLE #BListTemp
select TypeId INTO #BListTemp from FN_GetPowerRangeBList(@OperatorId,@Btypeid,'2,3,4,6')

--仓库多级权限
IF(OBJECT_ID('tempdb..#KListTemp') IS NOT NULL)
	DROP TABLE #KListTemp
select KtypeId INTO #KListTemp from FN_GetStockListOfBranch(@OperatorID,@BranchId,'')

--单据类型多级权限
IF(OBJECT_ID('tempdb..#VListTemp') IS NOT NULL)
	DROP TABLE #VListTemp
SELECT vchtype INTO #VListTemp FROM FN_GetPowerRangeVList(@BranchId)

--经手人多级权限
IF(OBJECT_ID('tempdb..#EListTemp') IS NOT NULL)
	DROP TABLE #EListTemp
SELECT TypeId INTO #EListTemp FROM FN_GetPowerRangeEList(@OperatorId,'')

--机构多级权限
IF(OBJECT_ID('tempdb..#BCListTemp') IS NOT NULL)
	DROP TABLE #BCListTemp
SELECT branchid INTO #BCListTemp FROM FN_GetPowerRangeBCList(@OperatorId,@BranchId)

IF(OBJECT_ID('tempdb..#DlyA') IS NOT NULL)  
 DROP TABLE #DlyA  
SELECT Btypeid,atypeid,branchid,EtypeId,VchType ,SUM(total) AS total INTO #DlyA FROM  dlya   WHERE (left(atypeid,10) in('0000100003','0000100004','0000300003','0000400003' )or 
	        atypeid IN('0000100005','0000200001'))
	        AND VchType IN(100,101,11,45,26,24,13,12,222,224,4,36,93,115,66)
	        and (date between @szStartDate and @szEndDate)
	        GROUP BY Btypeid,atypeid,branchid,EtypeId,VchType
    
  select  n.typeid as Btypeid,-isnull(d.qty,0)as qty,    
   -isnull(d.Total,0) as Total,    
   isnull(da.ArTotal,0)-isnull(db.apTotal,0) as ArTotal,    
   -isnull(d.Total,0)-(-isnull(d.CostTotal,0)) as Profittotal,    
   -isnull(d.CostTotal,0) as CostTotal,isnull(do.otherTotal,0) as OtherTotal,    
   isnull(de.ExpenseTotal,0) as ExpenseTotal,    
   -isnull(d.Total,0)-(-isnull(d.CostTotal,0))-isnull(ExpenseTotal,0) as  GainTotal,      
   isnull(dn.BackTotal,0) as BackTotal,    
   isnull(da.ArTotal,0)-isnull(db.apTotal,0)-isnull(dn.BackTotal,0) as ArrearageTotal        
  from     
     (  
	  /*  
	  select Typeid  from Btype  Where deleted=0  and left(typeid,5) not in('00001','00006','00007')       
	     and left(typeid,len(@Btypeid))=@Btypeid and sonnum=0          
	  */  
  	SELECT TypeId FROM #btypeBtypeSaleList  
      ) n       
     left join     
     (  
	  select  Btypeid,sum(qty)as qty,    
	         sum(BargainTotal) Total,sum(total) as ArTotal ,    
	         sum(costTotal) as CostTotal,    
	         sum(case when vchtype in(100,101) then Salemoney - tax_Total else 0 end) as zgccTotal    
	        from dlyData     
	        where  billtype=2 and vchtype in (100,101,11,45,26,24,13,12,222,224) and usedtype =case when vchtype in(222,224) then 1 else usedtype end 
	         and left(Btypeid,len(@Btypeid))=@Btypeid  and (date between @szStartDate and @szEndDate)         	         
		     and exists(select 1  from #BListTemp FilterB  where dlyData.BtypeId = FilterB.TypeId)    --权限	     
	     	 and exists(select 1  from #KListTemp FilterK where dlyData.ktypeId = Filterk.KtypeId ) 	 --权限    
	     	 and exists(select 1  from #VListTemp FilterV where dlyData.vchtype=FilterV.vchtype) 				 --权限	
	     	 and exists(select 1  from #EListTemp FilterE  where dlyData.EtypeId = FilterE.TypeId)  
	     
	         group by Btypeid   
     )d   on n.typeid=d.Btypeid      
      left join          
     (  
	  Select  Btypeid,sum(Total) as ArTotal                
	  from #DlyA   dlya    
	         where atypeid='0000100005'      
	     		and left( Btypeid ,len(@Btypeid))=@Btypeid           			
			and exists(SELECT 1 FROM  #BCListTemp FilterVC where dlya.branchid = FilterVC.branchid)      --权限
			and exists(select 1  from #BListTemp FilterB  where dlya.BtypeId = FilterB.TypeId)    --权限	   
			and exists(select 1  from #EListTemp FilterE  where dlya.EtypeId = FilterE.TypeId)    			
			--财务类单据，保存时没有仓库，不能进行仓库过滤 
			and branchid like @BranchId+'%'
	         group by  Btypeid  
     ) da on n.Typeid=da.Btypeid      
     left join       
     (  
	  Select  Btypeid,sum(Total) as ApTotal               
	  from #DlyA dlya      
	  where atypeid='0000200001'       
	     	and left( Btypeid ,len(@Btypeid))=@Btypeid       
		and exists(SELECT 1 FROM  #BCListTemp FilterVC where dlya.branchid = FilterVC.branchid)      --权限
		and exists(select 1  from #BListTemp FilterB  where dlya.BtypeId = FilterB.TypeId)    --权限	   
		and exists(select 1  from #EListTemp FilterE  where dlya.EtypeId = FilterE.TypeId)    		  	
		--财务类单据，保存时没有仓库，不能进行仓库过滤 
		and branchid like @BranchId+'%'	
	        Group by  Btypeid  
     ) db on n.typeid=db.Btypeid    
     left join       
     (  
	  Select  Btypeid,sum(a.Total) as OtherTotal         	     
	  from #DlyA  a    
	  where left(a.atypeid,10)='0000300003'    
	      and  left( Btypeid ,len(@Btypeid))=@Btypeid       
	      and exists(SELECT 1 FROM  #BCListTemp FilterVC where a.branchid = FilterVC.branchid)      --权限
	      and exists(select 1  from #BListTemp FilterB  where a.BtypeId = FilterB.TypeId)    --权限	
	      and exists(select 1  from #EListTemp FilterE  where a.EtypeId = FilterE.TypeId)        		  		
	      --财务类单据，保存时没有仓库，不能进行仓库过滤 
	      and branchid like @BranchId+'%'	 
	      Group by  Btypeid   
     ) do on n.typeid=do.Btypeid      
     left join       
     (  
	  Select  Btypeid, sum(a.Total) as ExpenseTotal               
	  from #DlyA  a    
	  where left(a.atypeid,10)='0000400003'    
	         and  left( Btypeid ,len(@Btypeid))=@Btypeid    
		 and exists(SELECT 1 FROM  #BCListTemp FilterVC where a.branchid = FilterVC.branchid)      --权限
		 and exists(select 1  from #BListTemp FilterB  where a.BtypeId = FilterB.TypeId)    --权限	
		 and exists(select 1  from #EListTemp FilterE  where a.EtypeId = FilterE.TypeId)        			  			  	 
		 --财务类单据，保存时没有仓库，不能进行仓库过滤 
		 and branchid like @BranchId+'%'
	  Group by  Btypeid   
     ) de on n.typeid=de.Btypeid    
     left join       
     (  
	  Select  Btypeid, sum(case a.atypeid when '0000299999' then -a.Total else a.total end) as BackTotal               
	  from #DlyA  a       --回款合计    
	  where (left(a.atypeid,10) in('0000100003','0000100004') or a.atypeid ='000040000300006'   or a.atypeid='0000299999')                 
		and exists(SELECT 1 FROM  #BCListTemp FilterVC where a.branchid = FilterVC.branchid)      --权限
		and exists(select 1  from #BListTemp FilterB  where a.BtypeId = FilterB.TypeId)    --权限	
		and exists(select 1  from #EListTemp FilterE  where a.EtypeId = FilterE.TypeId)        		  			  	 	       
		--财务类单据，保存时没有仓库，不能进行仓库过滤 
		and branchid like @BranchId+'%'
	  Group by Btypeid  
      ) dn     
      on n.typeid=dn.Btypeid    

  
 Drop Table #btypeBtypeSaleList  
 DROP TABLE #BListTemp  
 DROP TABLE #KListTemp   
 DROP TABLE #VListTemp 
 DROP TABLE  #EListTemp
 DROP TABLE #BCListTemp
 DROP TABLE  #DlyA


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO
 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[OtherStockInOutQuery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROC OtherStockInOutQuery
 GO
CREATE PROCEDURE OtherStockInOutQuery  
    ( 
      @szParID VARCHAR(8000)='', --父亲id 查询所有商品时传‘00000’   
      @Ptypeid VARCHAR(100) ,  
      @Ctypeid VARCHAR(50) , 
      @Etypeid varchar(50) ,  
      @Ktypeid varchar(50) ,  
      @Btypeid VARCHAR(50), 
      @Sizeid INT ,  
      @Colorid INT ,  
      @BillDate_s VARCHAR(12) ,  
      @BillDate_e VARCHAR(12) ,  
      @vchcode int ,    --类型名称  251表示其它出库单 ,252表示其它入库单
      @OperatorId VARCHAR(50),  
      @cMode VARCHAR(5)  
    )  
AS  
    if @cMode = 'S'  
    BEGIN  
     SELECT  PR.TypeID  AS PtypeID ,  
             case @vchcode when 251 then -sum(d.qty) else sum(d.qty) end as qty ,   
      case @vchcode when 251 then -sum(d.total) else sum(d.total) end as total ,  
      case @vchcode when 251 then -sum(d.retailprice*d.qty) else sum(d.retailprice*d.qty) end as retailTotal  
     FROM    dbo.DlyData d  
             INNER JOIN dlyndx n ON d.vchcode = n.vchcode 
             INNER JOIN (SELECT pt.TypeID FROM FN_GetPowerRangePTree(@OperatorId, @szParID) pt)PR 
             ON LEFT(d.PtypeID,LEN(PR.typeid))=PR.typeid
     WHERE   d.vchtype  = @vchcode   
             AND n.redold = 'F' 
             AND d.Date BETWEEN @BillDate_s AND @BillDate_e  
      and d.etypeid like @Etypeid + '%'  
      and d.ktypeid like @Ktypeid + '%'  
      AND d.BtypeId LIKE @Btypeid+'%'
      AND d.BranchId LIKE @Ctypeid+'%'
             AND EXISTS ( SELECT 1  
                          FROM   FN_GetPowerRangeBCList(@OperatorId, @ctypeid) FilterBC  
                          WHERE  n.Branchid = FilterBC.branchid )  
             AND EXISTS ( SELECT 1  
                          FROM   FN_GetPowerRangePlist(@OperatorId, @Ptypeid) FilterP  
                          WHERE  d.ptypeid = FilterP.typeid )                
     group by PR.TypeID
    end  
  
  /*列表模式*/
  
    if @cMode = 'L'  
    BEGIN   
     SELECT  d.PtypeID ,
             case @vchcode when 251 then -sum(d.qty) else sum(d.qty) end as qty ,  
      case @vchcode when 251 then -sum(d.total) else sum(d.total) end as total ,  
      case @vchcode when 251 then -sum(retailprice*d.qty) else sum(retailprice*d.qty) end as retailTotal  
     FROM    dbo.DlyData d  
             INNER JOIN dlyndx n ON d.vchcode = n.vchcode  
     WHERE   d.vchtype  = @vchcode   
             AND n.redold = 'F'  
      and d.etypeid like @Etypeid + '%'  
      and d.ktypeid like @Ktypeid + '%'  
      AND d.BtypeId LIKE @Btypeid+'%'
      AND d.BranchId LIKE @Ctypeid+'%'
             AND d.Date BETWEEN @BillDate_s AND @BillDate_e  
             AND EXISTS ( SELECT 1  
                          FROM   FN_GetPowerRangeBCList(@OperatorId, @ctypeid) FilterBC  
                          WHERE  n.Branchid = FilterBC.branchid )  
             AND EXISTS ( SELECT 1  
                          FROM   FN_GetPowerRangePlist(@OperatorId, @Ptypeid) FilterP  
                          WHERE  d.ptypeid = FilterP.typeid )  
     group by d.PtypeID,d.Colorid 
    end  
  
  
  
    /*明细模式*/
    if @cMode = 'M'  
    begin  
     SELECT  d.PtypeID ,  
      RIGHT('00000' + CAST(ds.ColorID AS VARCHAR), 5) pctypeid ,  
      RIGHT('00000' + CAST(ds.sizeid AS VARCHAR), 5) pstypeid ,  
      case @vchcode when 251 then -sum(ds.qty) else sum(ds.qty) end as qty ,  
      case @vchcode when 251 then -sum(ds.total) else sum(ds.total) end as total ,   
      case @vchcode when 251 then -sum(retailprice*ds.qty) else sum(retailprice*ds.qty) end as retailTotal  
     FROM    dbo.DlyData d  
             INNER JOIN dlyndx n ON d.vchcode = n.vchcode  
      inner join dlydatadetail ds on d.dlyorder = ds.dlyorder  
     WHERE   d.vchtype  = @vchcode   
             AND n.redold = 'F'  
      and d.etypeid like @Etypeid + '%'  
      and d.ktypeid like @Ktypeid + '%'  
      AND d.BtypeId LIKE @Btypeid+'%'
      AND d.BranchId LIKE @Ctypeid+'%'
      AND (@SizeID = -1 OR ds.SizeID = @SizeID)    
      AND (@ColorID = -1 OR ds.ColorID = @ColorID)   
             AND d.Date BETWEEN @BillDate_s AND @BillDate_e  
             AND EXISTS ( SELECT 1  
                          FROM   FN_GetPowerRangeBCList(@OperatorId, @ctypeid) FilterBC  
                          WHERE  n.Branchid = FilterBC.branchid )  
             AND EXISTS ( SELECT 1  
                          FROM   FN_GetPowerRangePlist(@OperatorId, @Ptypeid) FilterP  
                          WHERE  d.ptypeid = FilterP.typeid )  
     group by d.PtypeID,ds.colorid , ds.sizeid  
    end  
  go
  
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[GetStoreRetail]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[GetStoreRetail]
GO

SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO
/*      
商店零售分析
*/      
Create PROC GetStoreRetail
(      
  @dynTable as DynParameterTable readonly
  , @sqlCmd nvarchar(max) out --输出参数, 业务Sql片段
  , @decSql nvarchar(max) out --输出参数，参数声明Sql片段
  , @specSql nvarchar(max) out --输出参数，参数赋值Sql片段    
)       
AS 
BEGIN

DECLARE @SQLCmd1 VARCHAR(MAX)

SET @SQLCmd1 = N''
set @decSql = N'@dynParamTable as DynParameterTable readonly'
set @specSql = N'@dynParamTable'

SELECT @decSql += nchar(10) + nchar(9) + N', @' + ParaField + N' ' + DataType,
	   @specSql += nchar(10) + nchar(9) + isnull(N', ''' + ParaValue + N'''', ', null')
from @dynTable
WHERE datatype <> ''

declare @type varchar(100)
declare @type1 varchar(100)
declare @SortSql varchar(100)
select @type=ParaValue From @dynTable where ParaField='dlistfield'
SET @type =replace(REPLACE(@type,'branchid','N.branchid'),'etypeid','N.etypeid')
SET @type1 =replace(@type,'N.','')
SET @SortSql =replace(@type,'N.','Data.')
SET @SortSql =replace(@SortSql,'branchid','branchid desc')
SET @SortSql =replace(@SortSql,'etypeid','etypeid desc')


SET @SQLCmd1 ='
DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 

IF(OBJECT_ID(''''tempdb..#BillIndex171473380'''') IS NOT NULL)
	DROP TABLE #BillIndex171473380
SELECT '+@type+',D.qty,D.vchcode,ds.bargaintotal,ds.qty AS	toqty
INTO #BillIndex171473380
FROM dbo.DlyData D
INNER JOIN dbo.DlyDataDetail ds ON D.dlyorder = ds.dlyorder
INNER JOIN dlyndx N ON D.vchcode=N.vchcode
INNER JOIN ptype P ON P.typeid=D.ptypeid WHERE D.vchtype IN (12,100)
AND N.redold=''''F''''
AND D.Date between @billdate_s and @billdate_e
AND EXISTS (select 1 from dbo.FN_GetStockListOfBranch(@oprid,'''''''','''''''') WHERE KtypeId = D.KtypeId)	--仓库多级权限
AND EXISTS (select 1 from dbo.FN_GetPowerRangePList(@oprid,'''''''') PList WHERE PList.TypeID = D.Ptypeid AND PList.[stop] IN (CASE stop WHEN 1 THEN @containsstop ELSE 0 END)) 
AND (N.branchid LIKE @branchid OR @branchid IS NULL)
AND (D.PtypeId LIKE @ptypeid OR @ptypeid IS NULL)
AND (N.KtypeId LIKE @ktypeid OR @ktypeid IS NULL)
AND (N.Etypeid LIKE @etypeid OR @etypeid IS NULL)
AND (ds.colorId = @pcrec OR @pcrec IS NULL) 
AND (ds.sizeId = @psrec OR @psrec IS NULL)
AND (@assist1 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = D.PtypeId AND pa.AttributeID = @assist1))
AND (@assist2 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = D.PtypeId AND pa.AttributeID = @assist2))
AND (@assist3 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = D.PtypeId AND pa.AttributeID = @assist3))
AND (@assist4 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = D.PtypeId AND pa.AttributeID = @assist4))
AND (@assist5 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = D.PtypeId AND pa.AttributeID = @assist5))
AND (@assist6 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = D.PtypeId AND pa.AttributeID = @assist6))
AND (@assist7 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = D.PtypeId AND pa.AttributeID = @assist7))
AND (@assist8 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = D.PtypeId AND pa.AttributeID = @assist8))
AND (@definename IS NULL OR (custvalue1 LIKE @definename OR custvalue2 LIKE @definename OR custvalue3 LIKE @definename OR custvalue4 LIKE @definename OR custvalue5 LIKE @definename OR custvalue6 LIKE @definename))

IF object_id(''''tempdb..#tmpsort'''') is not null
                drop table #tmpsort
SELECT tmpsort.*,ROW_NUMBER() OVER (ORDER BY '+@type1+' DESC) levelorder
INTO #tmpsort
FROM ( 
	SELECT '+@type1+'
			,sum(isnull(lsqty,0)) as lsqty
			,sum(isnull(total,0)) as total
			,sum(isnull(xpqty,0)) as xpqty
			--连带率
			,case when sum(isnull(xpqty,0)) = 0 then 0 else round(CAST(sum(isnull(lsqty,0)) AS NUMERIC(24,10))/CAST(sum(isnull(xpqty,0)) AS NUMERIC(24,10)),2) end as joinrate	
			--平均客单价
			,case when sum(isnull(xpqty,0)) = 0 then 0 else round(CAST(sum(isnull(total,0)) AS NUMERIC(24,10))/CAST(sum(isnull(xpqty,0)) AS NUMERIC(24,10)),@dig_price) end as avgprice	
			--平均销售单价
			,case when sum(isnull(lsqty,0)) = 0 then 0 else round(CAST(sum(isnull(total,0)) AS NUMERIC(24,10))/CAST(sum(isnull(lsqty,0)) AS NUMERIC(24,10)),@dig_price) end as avgtotal	
	FROM (
		SELECT '+@type1+',-SUM(ISNULL(toqty,0)) AS lsqty,-SUM(ISNULL(bargaintotal,0))AS total,0 AS xpqty 
		FROM #BillIndex171473380 d 
		GROUP BY '+@type1+'
		UNION ALL 
		SELECT '+@type1+',0 AS lsqty,0 AS total,SUM(xpqty) AS xpqty 
		FROM (
			SELECT vchcode ,'+@type1+',CASE WHEN SUM(ISNULL(-bargaintotal,0)) >= 0 THEN 1 ELSE -1 END xpqty  FROM #BillIndex171473380 GROUP BY vchcode,'+@type1+'
		)Q 
		GROUP BY '+@type1+'
	) C 
	 GROUP BY '+@type1+'
) tmpsort; 

/*最终结果表*/
with Data AS (
SELECT * FROM #tmpsort
),'


-- 排序信息
declare @sortInfo varchar(255) = isnull((select ParaValue from @dynTable where ParaField = '__SortInfo__') + ',', '')
-- 排序联接信息
declare @sortJoinInfo varchar(555) = isnull((select replace(ParaValue, '__LeftTable__', 'Data') from @dynTable where ParaField = '__SortJoinInfo__'), '')
	
set @sqlCmd = cast(
(
	@SQLCmd1
	+ '
	__ReportData__ AS (
	select dense_rank() over (order by ' + @sortInfo + @SortSql+') __RowNo__,DATA.*
	from Data ' + @sortJoinInfo + ')'
) as nvarchar(max))

END

--历史备份
--SET QUOTED_IDENTIFIER ON 
--GO
--SET ANSI_NULLS ON 
--GO

--IF EXISTS ( SELECT  *
--            FROM    dbo.sysobjects
--            WHERE   id = OBJECT_ID(N'[dbo].[GetStoreRetail]')
--                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
--    DROP PROCEDURE [dbo].[GetStoreRetail]
--GO


----  ********************************************************************************************  
----  ||                                         
----  ||                                                 
----  ||   过程名称：GetStoreRetail                                       
----  ||   过程功能：商店零售分析 
----  ||
----  ||
----  ||==========================================================================================  
--CREATE   PROCEDURE GetStoreRetail
--(
	
	
--	@BranchID               VARCHAR(50),	--机构
--	@KtypeId   	  VARCHAR(50) ,
--	@LDBeginDate           	VARCHAR(50),	--录单开始日期      
--	@LDEndDate             	VARCHAR(50),	--录单结束日期
--	@CustomFieldValue	VARCHAR(50),	--自定义值
--	@PtypeID                VARCHAR(50),	--商品 
--	@colorID	int,		--颜色Id
--	@sizeID         int,		--尺码ID
-- 	@Assist1	VARCHAR(10),		--辅助类型值Id
-- 	@Assist2	VARCHAR(10),		--辅助类型值Id
-- 	@Assist3	VARCHAR(10),		--辅助类型值Id
-- 	@Assist4	VARCHAR(10),		--辅助类型值Id
-- 	@Assist5	VARCHAR(10),		--辅助类型值Id
-- 	@Assist6	VARCHAR(10),		--辅助类型值Id
-- 	@Assist7	VARCHAR(10),		--辅助类型值Id
-- 	@Assist8	VARCHAR(10),		--辅助类型值Id
-- 	@ISContainStop   INT,           --  是否包含停用商品
--	@OperatorId	VARCHAR(50)		--操作员Id 
--)
--as 
--begin


-- DECLARE @TempTableBillIndex VARCHAR(2000)
-- SET @TempTableBillIndex='##BillIndex'+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()))

--DECLARE @SQLText  VARCHAR(8000)

--set @SQLText='
--		select n.branchId,d.qty,d.vchcode,ds.bargaintotal,ds.qty as toqty
--		INTO '+@TempTableBillIndex +'
--		from dbo.DlyData d 
--		inner join dbo.DlyDataDetail ds on d.dlyorder = ds.dlyorder
--		inner join dlyndx n on d.vchcode=n.vchcode
--		inner join ptype p on p.typeid=d.ptypeid'
		    			
--DECLARE @WhereCmd VARCHAR(1000)
--SET @WhereCmd = '' 
--DECLARE @NeedAssist INT
--SET @NeedAssist = 0 
--select @SQLText = @SQLText +' where d.vchtype IN (12,100)
--			and n.redold=''F''
--     			and d.Date between '''+@LDBeginDate+'''  and '''+@LDEndDate+'''
--     			and exists(SELECT 1 FROM FN_GetPowerRangeBCList('''+@OperatorId+''','''+@branchId+''') FilterBC WHERE n.Branchid = FilterBC.branchid)
--     			and exists(SELECT 1  FROM FN_GetPowerRangePList('''+@OperatorId+''','''+@ptypeid+''') FilterP WHERE d.ptypeid = FilterP.typeid)
--     			'
--     	if @BranchID<>''
--	begin
--		select @SQLText=@SQLText+' and n.branchid like '''+@BranchID+'%'''
--	end 
--	IF @Ptypeid <> ''
--	BEGIN
--		select @SQLText=@SQLText + ' AND d.PtypeId LIKE '''+ @ptypeid+'%'''
--	END
--	IF @Ktypeid<>''
--		select @SQLText=@SQLText + ' and n.KtypeId like '''+@Ktypeid+'%'''

--        IF @ISContainStop = 0   --不包含停用商品
--		select @SQLText=@SQLText+ ' and p.Stop = 0'                                
--	if @colorID<>0
--	BEGIN
--	select @SQLText=@SQLText+' and ds.colorId=' + CAST( @colorID AS VARCHAR(10) )
--	END 
--	if @sizeID<>0
--	BEGIN
--	select @SQLText=@SQLText+'  and ds.sizeId=' + CAST( @sizeID AS VARCHAR(10) ) 
--	END 
--	IF @Assist1<>''
--	BEGIN
--		select @SQLText=@SQLText +' AND EXISTS (SELECT * FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = '+@Assist1 + ' )'
--	END
--	IF @Assist2<>''
--	BEGIN
--		select @SQLText=@SQLText +' AND EXISTS (SELECT * FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = '+@Assist2 + ' )'
		
--	END
--	IF @Assist3<>''
--	BEGIN
--		select @SQLText=@SQLText +' AND EXISTS (SELECT * FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = '+@Assist3 + ' )'
		
--	END
--	IF @Assist4<>''
--	BEGIN
--		select @SQLText=@SQLText +' AND EXISTS (SELECT * FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = '+@Assist4 + ' )'
		
--	END
--	IF @Assist5<>''
--	BEGIN
--		select @SQLText=@SQLText+' AND EXISTS (SELECT * FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = '+@Assist5 + ' )' 
		
--	END
--	IF @Assist6<>''
--	BEGIN
--		select @SQLText=@SQLText +' AND EXISTS (SELECT * FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = '+@Assist6 + ' )' 
		
--	END
--	IF @Assist7<>''
--	BEGIN
--		select @SQLText=@SQLText +' AND EXISTS (SELECT * FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = '+@Assist7 + ' )' 
		
--	END
--	IF @Assist8<>''
--	BEGIN
--		select @SQLText=@SQLText +' AND EXISTS (SELECT * FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = d.PtypeId AND pa.AttributeID = '+@Assist8 + ' )'
		
--	END
	
	
	
--	IF @CustomFieldValue <>''	--自定义类型值
--	BEGIN
--		select @SQLText = @SQLText + 'AND (d.custvalue1 ='''+ @CustomFieldValue +''' or custvalue2 ='''+ @CustomFieldValue +''' or custvalue3 ='''+ @CustomFieldValue +''' or custvalue4 ='''+ @CustomFieldValue +''' or custvalue5 ='''+ @CustomFieldValue +''' or custvalue6 ='''+ @CustomFieldValue + ''')'
--	END 

--PRINT @SQLText 
--EXEC(@SQLText)
--set @SQLText=''
--DECLARE @SQLList  VARCHAR(2000)
--DECLARE @SQLFrom  VARCHAR(1000)

---- 基本的显示字段
--SELECT @SQLList = ' select branchid,sum(isnull(lsqty,0)) as lsqty,sum(isnull(total,0)) as total,sum(isnull(xpqty,0)) as xpqty from
--	(select d.branchid,-sum(isnull(toqty,0)) as lsqty,-sum(isnull(bargaintotal,0))as total,0 as  xpqty
				
--				'
---- 基本列表的SQLFROM '+@TempTableBillIndex+'
--SELECT @SQLFrom=' 
--from '+@TempTableBillIndex+' d group by branchid
--union all

--select q.branchid as branchid,0 as lsqty,0 as total,count(vchcode) as xpqty 
--from (select distinct vchcode ,branchid from '+@TempTableBillIndex+' where isnull(toqty,0)<0 )q group by q.branchid
--) C 
-- group by branchid
--'

--SELECT @SQLText = @SQLList + @SQLFrom 

--EXEC(@SQLText)
--PRINT @SQLText
--EXEC ('DROP TABLE '+@TempTableBillIndex)
--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].[GetIPlist]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetIPlist]
GO




/*
	作者：cqh
	日期：2011-08-24
	描述：返回IP字符串
	实例：
			GetIPlist(2)
*/

CREATE  FUNCTION GetIPlist 
 ( 
    @etypeid varchar(100)
 ) 
returns varchar(1000)
--@ENCODE$--
AS 
BEGIN 
	DECLARE @returnstr varchar(2000)
	SET @returnstr =''
	
	
	select @returnstr=ipaddr FROM (SELECT ipaddr=
	  (select IpAddr+'~'+REVERSE(REVERSE(rtrim(ltrim(ipmax)))+substring(REVERSE(IpAddr),charindex('.',REVERSE(IpAddr)),len(IpAddr)))+'    ' FROM LoginIP  where EtypeID =@etypeid
	  FOR XML PATH(''))
  FROM LoginIP 
  where EtypeID =@etypeid)x


	
	return @returnstr
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/****** Object:  StoredProcedure [dbo].[FzGetAllPowerPro]    Script Date: 03/13/2012 16:01:35 ******/
IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[FZGetAllJXC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].FZGetAllJXC
GO


/****** Object:  StoredProcedure [dbo].[FZGetAllJXC]    Script Date: 03/13/2012 16:01:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].FZGetAllJXC
(
      @BranchId varchar(8000) ,
      @PtypeId varchar(50) ,
      @KtypeId varchar(8000) ,
      @DateBegin varchar(15) ,
      @DateEnd varchar(15) ,
      @Displaymode int ,
      @OperatorId VARCHAR(50),
      @OnlyCheckChange bit = 0
)
as
begin

	Declare @NdxMaxId int
	Declare @QryMaxId int
	select @NdxMaxId = MAX(vchcode) from dlyndx
	select @QryMaxId = cast(subvalue as int) from QueryVchcodeRec where subname = 'AllPowerMaxVch'
	--新增存储过程 GetDig，用来取小数配置。以后所有报表存储过程对小数位的取舍用以下方式。
    DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
    EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
	
	if (@NdxMaxId > @QryMaxId) or exists(select 1 from TBAllPowerChangeVchcode where vchcode <= @QryMaxId)
	begin
	        if object_id('tempdb..#InoutVchTypeTemp') is not null 
	        	drop table #InoutVchTypeTemp
		Delete from TBAllPowerChangeVchcode where vchcode > @QryMaxId		
		Create Table #InoutVchTypeTemp
		(
		 VchType int,
		 DetailType int,
		 Phid int
		)
			insert into #InoutVchTypeTemp select vchtype,detailtype,phid from 
			(Select 34 as vchtype,101 as detailtype,0 as phid union all
			Select 45 as vchtype,102 as detailtype,0 as phid union all
			Select 101 as vchtype,102 as detailtype,0 as phid union all
			Select 16 as vchtype,103 as detailtype,0 as phid union all
			Select 14 as vchtype,104 as detailtype,0 as phid union all		
			Select 126 as vchtype,105 as detailtype,0 as phid union all
			Select 17 as vchtype,106 as detailtype,0 as phid union all
			Select 21 as vchtype,107 as detailtype,0 as phid union all
			Select 24 as vchtype,108 as detailtype,0 as phid union all
			Select 57 as vchtype,109 as detailtype,0 as phid union all
			Select 13 as vchtype,112 as detailtype,0 as phid union all
			Select 101 as vchtype,112 as detailtype,0 as phid union all
			Select 100 as vchtype,112 as detailtype,0 as phid union all
			Select 12 as vchtype,112 as detailtype,0 as phid union all
			Select 212 as vchtype,113 as detailtype,1 as phid union all
			Select 218 as vchtype,113 as detailtype,1 as phid union all
			Select 212 as vchtype,113 as detailtype,3 as phid union all
			Select 218 as vchtype,113 as detailtype,3 as phid union all
			Select 224 as vchtype,115 as detailtype,0 as phid union all
			Select 230 as vchtype,116 as detailtype,0 as phid union all
			Select 212 as vchtype,118 as detailtype,2 as phid union all
			Select 218 as vchtype,118 as detailtype,2 as phid union all
			Select 150 as vchtype,120 as detailtype,0 as phid union all
			Select 252 as vchtype,121 as detailtype,0 as phid union all
			Select 11 as vchtype,201 as detailtype,0 as phid union all
			Select 6 as vchtype,202 as detailtype,0 as phid union all
			Select 16 as vchtype,203 as detailtype,0 as phid union all
			Select 139 as vchtype,204 as detailtype,0 as phid union all
			Select 17 as vchtype,205 as detailtype,0 as phid union all
			Select 9 as vchtype,206 as detailtype,0 as phid union all
			Select 21 as vchtype,207 as detailtype,0 as phid union all
			Select 24 as vchtype,208 as detailtype,0 as phid union all
			Select 57 as vchtype,209 as detailtype,0 as phid union all
			Select 13 as vchtype,212 as detailtype,0 as phid union all
			Select 101 as vchtype,212 as detailtype,0 as phid union all
			Select 100 as vchtype,212 as detailtype,0 as phid union all
			Select 12 as vchtype,212 as detailtype,0 as phid union all
			Select 212 as vchtype,213 as detailtype,1 as phid union all
			Select 212 as vchtype,213 as detailtype,3 as phid union all
			Select 218 as vchtype,213 as detailtype,1 as phid union all
			Select 218 as vchtype,213 as detailtype,3 as phid union all
			Select 222 as vchtype,215 as detailtype,0 as phid union all
			Select 224 as vchtype,215 as detailtype,0 as phid union all
			Select 230 as vchtype,216 as detailtype,0 as phid union all
			Select 212 as vchtype,218 as detailtype,2 as phid union all
			Select 218 as vchtype,218 as detailtype,2 as phid union all
			Select 150 as vchtype,220 as detailtype,0 as phid union all
			Select 251 as vchtype,221 as detailtype,0 as phid
			) a	

		Insert into TableForAllJXC select a.phid,b.PtypeId,c.ColorID,c.SizeID,b.BranchId,b.ktypeId,CONVERT(NUMERIC(24,10),sum(c.Qty)),CONVERT(NUMERIC(24,10),sum(c.CostTotal)),
		           CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (a.Usedtype='2' OR (a.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,c.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,c.AccountTime, 23 ) ELSE a.[date] END,
		           x.DetailType
		From DlyNdx a inner join DlyData b on a.Vchcode = b.Vchcode inner join dlydatadetail c on b.DlyOrder = c.DlyOrder --inner join #AllJXCKtypeIdTable f on b.KtypeId = f.KtypeId
			  Inner join #InoutVchTypeTemp x on a.Vchtype = x.VchType and x.Phid = a.PhId 
				--由于红冲单据的存在 所以出入库不能用正负号判断，故去掉
			 AND  
			 (
				(
					(
						(( c.qty > 0) and x.DetailType < 200) 
						OR  
						(( c.qty < 0) and x.DetailType > 200)
					) 
					AND a.RedWord = 'F'
				)
				OR
				(
					(
						(( c.qty > 0) and x.DetailType > 200) 
						OR  
						(( c.qty < 0) and x.DetailType < 200)
					) 
					AND a.RedWord = 'T'
				)
			)
			and ((b.Vchcode > @QryMaxId) or (b.vchcode in (select vchcode from TBAllPowerChangeVchcode) and ((b.ktypeid = '99999' and b.Qty < 0) or b.usedtype = 2)))
			----将新增单据数据以及验收的老单据数据写入表中
		group by a.phid,b.PtypeId,c.ColorID,c.SizeID ,b.BranchId,b.ktypeId ,a.date,x.DetailType
		Order by a.date				
		drop table #InoutVchTypeTemp
		Update QueryVchcodeRec set subvalue = cast(@NdxMaxId as varchar) where subname = 'AllPowerMaxVch'		
		Delete from TBAllPowerChangeVchcode where vchcode <= @QryMaxId		
	end
		
    if object_id('tempdb..#AllJXCKtypeIdTable') is not null 
        drop table #AllJXCKtypeIdTable
    if object_id('tempdb..#AllJXCPtypeIdTable') is not null 
        drop table #AllJXCPtypeIdTable        
        
    select  KtypeId
    Into    #AllJXCKtypeIdTable
    from    FN_GetStockListOfBranch(@OperatorID, @BranchId, @Ktypeid) a
    where   exists ( select 1
                     from   Stock b
                     where  a.ktypeid = b.typeid
                            and b.branchtype <> 4 )
	create CLUSTERED index TempIdx1 on #AllJXCKtypeIdTable(Ktypeid)                             

	Select typeId,retailPrice
	Into #AllJXCPtypeIdTable
	from FN_GetPowerRangePList(@OperatorId, @PtypeId) a
        where @OnlyCheckChange = 0 or (@OnlyCheckChange = 1 and exists (Select 1 from TableForAllJXC x where Datadate between @DateBegin and @DateEnd and a.typeId = x.PtypeId)) 
	
	create CLUSTERED index TempIdx2 on #AllJXCPtypeIdTable(typeId)                    
	
    if @DisplayMode = 0 
        begin
			select Ptypeid,case when (detailtype > 200 and detailtype < 300) then -SUM(Qty) else SUM(Qty) end as qty,
				case when (detailtype > 200 and detailtype < 300) then -SUM(CostTotal) else SUM(CostTotal) end as costtotal,	detailtype,
						CASE WHEN (detailtype > 200 and detailtype < 300) THEN -sum(RetailTotal) ELSE sum(RetailTotal) END as RetailTotal into #TempAllJXC1 from 
				(select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	detailtype,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as RetailTotal from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate between @DateBegin and @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,Left(PtypeId, Len(@PtypeId) + 5)
				union all
				select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,-SUM(Qty) as qty,-SUM(CostTotal) as costtotal,	401,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),-Qty)*CONVERT(NUMERIC(24,10),c.RetailPrice))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate > @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,Left(PtypeId, Len(@PtypeId) + 5) 
				union all
				select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	301,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate < @DateBegin
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by Left(PtypeId, Len(@PtypeId) + 5)
				union all (select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(qty) as qty,SUM(total) as costtotal,301 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from IniGoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by Left(PtypeId, Len(@PtypeId) + 5))
				union all (select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(qty) as qty,SUM(total) as costtotal,401 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from GoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by Left(PtypeId, Len(@PtypeId) + 5))						
				) a
				group by PtypeId,DetailType



				
            select  PtypeId ,
                                      isnull(sum(case DetailType
                                 when 101 then Qty
                                 else 0
                               end), 0) as Qty101 ,
                    isnull(sum(case DetailType
                                 when 101 then CostTotal
                                 else 0
                               end), 0) as Total101 ,
                    isnull(sum(case DetailType
                                 when 101 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal101 ,
                    isnull(sum(case DetailType
                                 when 102 then Qty
                                 else 0
                               end), 0) as Qty102 ,
                    isnull(sum(case DetailType
                                 when 102 then CostTotal
                                 else 0
                               end), 0) as Total102 ,
                    isnull(sum(case DetailType
                                 when 102 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal102 ,
                    isnull(sum(case DetailType
                                 when 103 then Qty
                                 else 0
                               end), 0) as Qty103 ,
                    isnull(sum(case DetailType
                                 when 103 then CostTotal
                                 else 0
                               end), 0) as Total103 ,
                    isnull(sum(case DetailType
                                 when 103 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal103 ,
                    isnull(sum(case DetailType
                                 when 104 then Qty
                                 else 0
                               end), 0) as Qty104 ,
                    isnull(sum(case DetailType
                                 when 104 then CostTotal
                                 else 0
                               end), 0) as Total104 ,
                    isnull(sum(case DetailType
                                 when 104 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal104 ,
                    isnull(sum(case DetailType
                                 when 105 then Qty
                                 else 0
                               end), 0) as Qty105 ,
                    isnull(sum(case DetailType
                                 when 105 then CostTotal
                                 else 0
                               end), 0) as Total105 ,
                    isnull(sum(case DetailType
                                 when 105 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal105 ,
                    isnull(sum(case DetailType
                                 when 106 then Qty
                                 else 0
                               end), 0) as Qty106 ,
                    isnull(sum(case DetailType
                                 when 106 then CostTotal
                                 else 0
                               end), 0) as Total106 ,
                    isnull(sum(case DetailType
                                 when 106 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal106 ,
                    isnull(sum(case DetailType
                                 when 107 then Qty
                                 else 0
                               end), 0) as Qty107 ,
                    isnull(sum(case DetailType
                                 when 107 then CostTotal
                                 else 0
                               end), 0) as Total107 ,
                    isnull(sum(case DetailType
                                 when 107 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal107 ,
                    isnull(sum(case DetailType
                                 when 108 then Qty
                                 else 0
                               end), 0) as Qty108 ,
                    isnull(sum(case DetailType
                                 when 108 then CostTotal
                                 else 0
                               end), 0) as Total108 ,
                    isnull(sum(case DetailType
                                 when 108 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal108 ,
                    isnull(sum(case DetailType
                                 when 109 then Qty
                                 else 0
                               end), 0) as Qty109 ,
                    isnull(sum(case DetailType
                                 when 109 then CostTotal
                                 else 0
                               end), 0) as Total109 ,
                    isnull(sum(case DetailType
                                 when 109 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal109 ,
                    isnull(sum(case DetailType
                                 when 110 then Qty
                                 else 0
                               end), 0) as Qty110 ,
                    isnull(sum(case DetailType
                                 when 110 then CostTotal
                                 else 0
                               end), 0) as Total110 ,
                    isnull(sum(case DetailType
                                 when 110 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal110 ,
                    isnull(sum(case DetailType
                                 when 112 then Qty
                                 else 0
                               end), 0) as Qty112 ,
                    isnull(sum(case DetailType
                                 when 112 then CostTotal
                                 else 0
                               end), 0) as Total112 ,
                    isnull(sum(case DetailType
                                 when 112 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal112 ,
                    isnull(sum(case DetailType
                                 when 113 then Qty
                                 else 0
                               end), 0) as Qty113 ,
                    isnull(sum(case DetailType
                                 when 113 then CostTotal
                                 else 0
                               end), 0) as Total113 ,
                    isnull(sum(case DetailType
                                 when 113 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal113 ,
                    isnull(sum(case DetailType
                                 when 114 then Qty
                                 else 0
                               end), 0) as Qty114 ,
                    isnull(sum(case DetailType
                                 when 114 then CostTotal
                                 else 0
                               end), 0) as Total114 ,
                    isnull(sum(case DetailType
                                 when 114 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal114 ,
                    isnull(sum(case DetailType
                                 when 115 then Qty
                                 else 0
                               end), 0) as Qty115 ,
                    isnull(sum(case DetailType
                                 when 115 then CostTotal
                                 else 0
                               end), 0) as Total115 ,
                    isnull(sum(case DetailType
                                 when 115 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal115 ,
                    isnull(sum(case DetailType
                                 when 116 then Qty
                                 else 0
                               end), 0) as Qty116 ,
                    isnull(sum(case DetailType
                                 when 116 then CostTotal
                                 else 0
                               end), 0) as Total116 ,
                    isnull(sum(case DetailType
                                 when 116 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal116 ,
                    isnull(sum(case DetailType
                                 when 118 then Qty
                                 else 0
                               end), 0) as Qty118 ,
                    isnull(sum(case DetailType
                                 when 118 then CostTotal
                                 else 0
                               end), 0) as Total118 ,
                    isnull(sum(case DetailType
                                 when 118 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal118 ,
                    isnull(sum(case DetailType
                                 when 120 then Qty
                                 else 0
                               end), 0) as Qty120 ,
                    isnull(sum(case DetailType
                                 when 120 then CostTotal
                                 else 0
                               end), 0) as Total120 ,
                    isnull(sum(case DetailType
                                 when 120 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal120 ,
                    isnull(sum(case DetailType
                                 when 121 then Qty
                                 else 0
                               end), 0) as Qty121 ,
                    isnull(sum(case DetailType
                                 when 121 then CostTotal
                                 else 0
                               end), 0) as Total121 ,
                    isnull(sum(case DetailType
                                 when 121 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal121 ,
                    isnull(sum(case DetailType
                                 when 201 then Qty
                                 else 0
                               end), 0) as Qty201 ,
                    isnull(sum(case DetailType
                                 when 201 then CostTotal
                                 else 0
                               end), 0) as Total201 ,
                    isnull(sum(case DetailType
                                 when 201 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal201 ,
                    isnull(sum(case DetailType
                                 when 202 then Qty
                                 else 0
                               end), 0) as Qty202 ,
                    isnull(sum(case DetailType
                                 when 202 then CostTotal
                                 else 0
                               end), 0) as Total202 ,
                    isnull(sum(case DetailType
                                 when 202 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal202 ,
                    isnull(sum(case DetailType
                                 when 203 then Qty
                                 else 0
                               end), 0) as Qty203 ,
                    isnull(sum(case DetailType
                                 when 203 then CostTotal
                                 else 0
                               end), 0) as Total203 ,
                    isnull(sum(case DetailType
                                 when 203 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal203 ,
                    isnull(sum(case DetailType
                                 when 204 then Qty
                                 else 0
                               end), 0) as Qty204 ,
                    isnull(sum(case DetailType
                                 when 204 then CostTotal
                                 else 0
                               end), 0) as Total204 ,
                    isnull(sum(case DetailType
                                 when 204 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal204 ,
                    isnull(sum(case DetailType
                                 when 205 then Qty
                                 else 0
                               end), 0) as Qty205 ,
                    isnull(sum(case DetailType
                                 when 205 then CostTotal
                                 else 0
                               end), 0) as Total205 ,
                    isnull(sum(case DetailType
                                 when 205 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal205 ,
                    isnull(sum(case DetailType
                                 when 206 then Qty
                                 else 0
                               end), 0) as Qty206 ,
                    isnull(sum(case DetailType
                                 when 206 then CostTotal
                                 else 0
                               end), 0) as Total206 ,
                    isnull(sum(case DetailType
                                 when 206 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal206 ,
                    isnull(sum(case DetailType
                                 when 207 then Qty
                                 else 0
                               end), 0) as Qty207 ,
                    isnull(sum(case DetailType
                                 when 207 then CostTotal
                                 else 0
                               end), 0) as Total207 ,
                    isnull(sum(case DetailType
                                 when 207 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal207 ,
                    isnull(sum(case DetailType
                                 when 208 then Qty
                                 else 0
                               end), 0) as Qty208 ,
                    isnull(sum(case DetailType
                                 when 208 then CostTotal
                                 else 0
                               end), 0) as Total208 ,
                    isnull(sum(case DetailType
                                 when 208 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal208 ,
                    isnull(sum(case DetailType
                                 when 209 then Qty
                                 else 0
                               end), 0) as Qty209 ,
                    isnull(sum(case DetailType
                                 when 209 then CostTotal
                                 else 0
                               end), 0) as Total209 ,
                    isnull(sum(case DetailType
                                 when 209 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal209 ,
                    isnull(sum(case DetailType
                                 when 210 then Qty
                                 else 0
                               end), 0) as Qty210 ,
                    isnull(sum(case DetailType
                                 when 210 then CostTotal
                                 else 0
                               end), 0) as Total210 ,
                    isnull(sum(case DetailType
                                 when 210 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal210 ,
                    isnull(sum(case DetailType
                                 when 212 then Qty
                                 else 0
                               end), 0) as Qty212 ,
                    isnull(sum(case DetailType
                                 when 212 then CostTotal
                                 else 0
                               end), 0) as Total212 ,
                    isnull(sum(case DetailType
                                 when 212 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal212 ,
                    isnull(sum(case DetailType
                                 when 213 then Qty
                                 else 0
                               end), 0) as Qty213 ,
                    isnull(sum(case DetailType
                                 when 213 then CostTotal
                                 else 0
                               end), 0) as Total213 ,
                    isnull(sum(case DetailType
                                 when 213 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal213 ,
                    isnull(sum(case DetailType
                                 when 214 then Qty
                                 else 0
                               end), 0) as Qty214 ,
                    isnull(sum(case DetailType
                                 when 214 then CostTotal
                                 else 0
                               end), 0) as Total214 ,
                    isnull(sum(case DetailType
                                 when 214 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal214 ,
                    isnull(sum(case DetailType
                                 when 215 then Qty
                                 else 0
                               end), 0) as Qty215 ,
                    isnull(sum(case DetailType
                                 when 215 then CostTotal
                                 else 0
                               end), 0) as Total215 ,
                    isnull(sum(case DetailType
                                 when 215 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal215 ,
                    isnull(sum(case DetailType
                                 when 216 then Qty
                                 else 0
                               end), 0) as Qty216 ,
                    isnull(sum(case DetailType
                                 when 216 then CostTotal
                                 else 0
                               end), 0) as Total216 ,
                    isnull(sum(case DetailType
                                 when 216 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal216 ,
                    isnull(sum(case DetailType
                                 when 218 then Qty
                                 else 0
                               end), 0) as Qty218 ,
                    isnull(sum(case DetailType
                                 when 218 then CostTotal
                                 else 0
                               end), 0) as Total218 ,
                    isnull(sum(case DetailType
                                 when 218 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal218 ,
                    isnull(sum(case DetailType
                                 when 220 then Qty
                                 else 0
                               end), 0) as Qty220 ,
                    isnull(sum(case DetailType
                                 when 220 then CostTotal
                                 else 0
                               end), 0) as Total220 ,
                    isnull(sum(case DetailType
                                 when 220 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal220 ,
                    isnull(sum(case DetailType
                                 when 221 then Qty
                                 else 0
                               end), 0) as Qty221 ,
                    isnull(sum(case DetailType
                                 when 221 then CostTotal
                                 else 0
                               end), 0) as Total221 ,
                    isnull(sum(case DetailType
                                 when 221 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal221 ,
                    isnull(sum(case DetailType
                                 when 301 then Qty
                                 else 0
                               end), 0) as Qty301 ,
                    isnull(sum(case DetailType
                                 when 301 then CostTotal
                                 else 0
                               end), 0) as Total301 ,
                    isnull(sum(case DetailType
                                 when 301 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal301 ,
                    isnull(sum(case DetailType
                                 when 401 then Qty
                                 else 0
                               end), 0) as Qty401 ,
                    isnull(sum(case DetailType
                                 when 401 then CostTotal
                                 else 0
                               end), 0) as Total401 ,
                    isnull(sum(case DetailType
                                 when 401 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal401
            from    #TempAllJXC1 a --where not (DetailType = 301 and (qty = 0 or CostTotal = 0)) 		
            group by PtypeId
	end                    
	
	if @Displaymode = 1 
	begin	        
			select PtypeId,case when (detailtype > 200 and detailtype < 300) then -SUM(Qty) else SUM(Qty) end as qty,
					case when (detailtype > 200 and detailtype < 300) then -SUM(CostTotal) else SUM(CostTotal) end as costtotal,	detailtype,
						CASE WHEN (detailtype > 200 and detailtype < 300) THEN -sum(RetailTotal) ELSE sum(RetailTotal) END as RetailTotal into #TempAllJXC2 from 
				(select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	detailtype,
						ROUND(CONVERT(NUMERIC(24,10),SUM(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as RetailTotal from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate between @DateBegin and @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,PtypeId
				union all
				select PtypeId,-SUM(Qty) as qty,-SUM(CostTotal) as costtotal,	401,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),-Qty)*CONVERT(NUMERIC(24,10),c.RetailPrice))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate > @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,PtypeId
				union all
				select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	301,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate < @DateBegin
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId
				union all (select Ptypeid,SUM(qty) as qty,SUM(total) as costtotal,301 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from IniGoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId)
				union all (select Ptypeid,SUM(qty) as qty,SUM(total) as costtotal,401 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from GoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId						
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId)							
				) a
				group by PtypeId,DetailType
			
				
            select  PtypeId ,
		    --(SELECT TOP 1 [Order] FROM [dbo].[Size] si WHERE right('00000' + CAST(si.SizeId as VARCHAR), 5)  = pstypeid ) AS psOrder , 
                    isnull(sum(case DetailType
                                 when 101 then Qty
                                 else 0
                               end), 0) as Qty101 ,
                    isnull(sum(case DetailType
                                 when 101 then CostTotal
                                 else 0
                               end), 0) as Total101 ,
                    isnull(sum(case DetailType
                                 when 101 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal101 ,
                    isnull(sum(case DetailType
                                 when 102 then Qty
                                 else 0
                               end), 0) as Qty102 ,
                    isnull(sum(case DetailType
                                 when 102 then CostTotal
                                 else 0
                               end), 0) as Total102 ,
                    isnull(sum(case DetailType
                                 when 102 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal102 ,
                    isnull(sum(case DetailType
                                 when 103 then Qty
                                 else 0
                               end), 0) as Qty103 ,
                    isnull(sum(case DetailType
                                 when 103 then CostTotal
                                 else 0
                               end), 0) as Total103 ,
                    isnull(sum(case DetailType
                                 when 103 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal103 ,
                    isnull(sum(case DetailType
                                 when 104 then Qty
                                 else 0
                               end), 0) as Qty104 ,
                    isnull(sum(case DetailType
                                 when 104 then CostTotal
                                 else 0
                               end), 0) as Total104 ,
                    isnull(sum(case DetailType
                                 when 104 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal104 ,
                    isnull(sum(case DetailType
                                 when 105 then Qty
                                 else 0
                               end), 0) as Qty105 ,
                    isnull(sum(case DetailType
                                 when 105 then CostTotal
                                 else 0
                               end), 0) as Total105 ,
                    isnull(sum(case DetailType
                                 when 105 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal105 ,
                    isnull(sum(case DetailType
                                 when 106 then Qty
                                 else 0
                               end), 0) as Qty106 ,
                    isnull(sum(case DetailType
                                 when 106 then CostTotal
                                 else 0
                               end), 0) as Total106 ,
                    isnull(sum(case DetailType
                                 when 106 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal106 ,
                    isnull(sum(case DetailType
                                 when 107 then Qty
                                 else 0
                               end), 0) as Qty107 ,
                    isnull(sum(case DetailType
                                 when 107 then CostTotal
                                 else 0
                               end), 0) as Total107 ,
                    isnull(sum(case DetailType
                                 when 107 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal107 ,
                    isnull(sum(case DetailType
                                 when 108 then Qty
                                 else 0
                               end), 0) as Qty108 ,
                    isnull(sum(case DetailType
                                 when 108 then CostTotal
                                 else 0
                               end), 0) as Total108 ,
                    isnull(sum(case DetailType
                                 when 108 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal108 ,
                    isnull(sum(case DetailType
                                 when 109 then Qty
                                 else 0
                               end), 0) as Qty109 ,
                    isnull(sum(case DetailType
                                 when 109 then CostTotal
                                 else 0
                               end), 0) as Total109 ,
                    isnull(sum(case DetailType
                                 when 109 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal109 ,
                    isnull(sum(case DetailType
                                 when 110 then Qty
                                 else 0
                               end), 0) as Qty110 ,
                    isnull(sum(case DetailType
                                 when 110 then CostTotal
                                 else 0
                               end), 0) as Total110 ,
                    isnull(sum(case DetailType
                                 when 110 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal110 ,
                    isnull(sum(case DetailType
                                 when 112 then Qty
                                 else 0
                               end), 0) as Qty112 ,
                    isnull(sum(case DetailType
                                 when 112 then CostTotal
                                 else 0
                               end), 0) as Total112 ,
                    isnull(sum(case DetailType
                                 when 112 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal112 ,
                    isnull(sum(case DetailType
                                 when 113 then Qty
                                 else 0
                               end), 0) as Qty113 ,
                    isnull(sum(case DetailType
                                 when 113 then CostTotal
                                 else 0
                               end), 0) as Total113 ,
                    isnull(sum(case DetailType
                                 when 113 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal113 ,
                    isnull(sum(case DetailType
                                 when 114 then Qty
                                 else 0
                               end), 0) as Qty114 ,
                    isnull(sum(case DetailType
                                 when 114 then CostTotal
                                 else 0
                               end), 0) as Total114 ,
                    isnull(sum(case DetailType
                                 when 114 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal114 ,
                    isnull(sum(case DetailType
                                 when 115 then Qty
                                 else 0
                               end), 0) as Qty115 ,
                    isnull(sum(case DetailType
                                 when 115 then CostTotal
                                 else 0
                               end), 0) as Total115 ,
                    isnull(sum(case DetailType
                                 when 115 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal115 ,
                    isnull(sum(case DetailType
                                 when 116 then Qty
                                 else 0
                               end), 0) as Qty116 ,
                    isnull(sum(case DetailType
                                 when 116 then CostTotal
                                 else 0
                               end), 0) as Total116 ,
                    isnull(sum(case DetailType
                                 when 116 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal116 ,
                    isnull(sum(case DetailType
                                 when 118 then Qty
                                 else 0
                               end), 0) as Qty118 ,
                    isnull(sum(case DetailType
                                 when 118 then CostTotal
                                 else 0
                               end), 0) as Total118 ,
                    isnull(sum(case DetailType
                                 when 118 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal118 ,
                    isnull(sum(case DetailType
                                 when 120 then Qty
                                 else 0
                               end), 0) as Qty120 ,
                    isnull(sum(case DetailType
                                 when 120 then CostTotal
                                 else 0
                               end), 0) as Total120 ,
                    isnull(sum(case DetailType
                                 when 120 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal120 ,
                    isnull(sum(case DetailType
                                 when 121 then Qty
                                 else 0
                               end), 0) as Qty121 ,
                    isnull(sum(case DetailType
                                 when 121 then CostTotal
                                 else 0
                               end), 0) as Total121 ,
                    isnull(sum(case DetailType
                                 when 121 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal121 ,
                    isnull(sum(case DetailType
                                 when 201 then Qty
                                 else 0
                               end), 0) as Qty201 ,
                    isnull(sum(case DetailType
                                 when 201 then CostTotal
                                 else 0
                               end), 0) as Total201 ,
                    isnull(sum(case DetailType
                                 when 201 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal201 ,
                    isnull(sum(case DetailType
                                 when 202 then Qty
                                 else 0
                               end), 0) as Qty202 ,
                    isnull(sum(case DetailType
                                 when 202 then CostTotal
                                 else 0
                               end), 0) as Total202 ,
                    isnull(sum(case DetailType
                                 when 202 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal202 ,
                    isnull(sum(case DetailType
                                 when 203 then Qty
                                 else 0
                               end), 0) as Qty203 ,
                    isnull(sum(case DetailType
                                 when 203 then CostTotal
                                 else 0
                               end), 0) as Total203 ,
                    isnull(sum(case DetailType
                                 when 203 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal203 ,
                    isnull(sum(case DetailType
                                 when 204 then Qty
                                 else 0
                               end), 0) as Qty204 ,
                    isnull(sum(case DetailType
                                 when 204 then CostTotal
                                 else 0
                               end), 0) as Total204 ,
                    isnull(sum(case DetailType
                                 when 204 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal204 ,
                    isnull(sum(case DetailType
                                 when 205 then Qty
                                 else 0
                               end), 0) as Qty205 ,
                    isnull(sum(case DetailType
                                 when 205 then CostTotal
                                 else 0
                               end), 0) as Total205 ,
                    isnull(sum(case DetailType
                                 when 205 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal205 ,
                    isnull(sum(case DetailType
                                 when 206 then Qty
                                 else 0
                               end), 0) as Qty206 ,
                    isnull(sum(case DetailType
                                 when 206 then CostTotal
                                 else 0
                               end), 0) as Total206 ,
                    isnull(sum(case DetailType
                                 when 206 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal206 ,
                    isnull(sum(case DetailType
                                 when 207 then Qty
                                 else 0
                               end), 0) as Qty207 ,
                    isnull(sum(case DetailType
                                 when 207 then CostTotal
                                 else 0
                               end), 0) as Total207 ,
                    isnull(sum(case DetailType
                                 when 207 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal207 ,
                    isnull(sum(case DetailType
                                 when 208 then Qty
                                 else 0
                               end), 0) as Qty208 ,
                    isnull(sum(case DetailType
                                 when 208 then CostTotal
                                 else 0
                               end), 0) as Total208 ,
                    isnull(sum(case DetailType
                                 when 208 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal208 ,
                    isnull(sum(case DetailType
                                 when 209 then Qty
                                 else 0
                               end), 0) as Qty209 ,
                    isnull(sum(case DetailType
                                 when 209 then CostTotal
                                 else 0
                               end), 0) as Total209 ,
                    isnull(sum(case DetailType
                                 when 209 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal209 ,
                    isnull(sum(case DetailType
                                 when 210 then Qty
                                 else 0
                               end), 0) as Qty210 ,
                    isnull(sum(case DetailType
                                 when 210 then CostTotal
                                 else 0
                               end), 0) as Total210 ,
                    isnull(sum(case DetailType
                                 when 210 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal210 ,
                    isnull(sum(case DetailType
                                 when 212 then Qty
                                 else 0
                               end), 0) as Qty212 ,
                    isnull(sum(case DetailType
                                 when 212 then CostTotal
                                 else 0
                               end), 0) as Total212 ,
                    isnull(sum(case DetailType
                                 when 212 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal212 ,
                    isnull(sum(case DetailType
                                 when 213 then Qty
                                 else 0
                               end), 0) as Qty213 ,
                    isnull(sum(case DetailType
                                 when 213 then CostTotal
                                 else 0
                               end), 0) as Total213 ,
                    isnull(sum(case DetailType
                                 when 213 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal213 ,
                    isnull(sum(case DetailType
                                 when 214 then Qty
                                 else 0
                               end), 0) as Qty214 ,
                    isnull(sum(case DetailType
                                 when 214 then CostTotal
                                 else 0
                               end), 0) as Total214 ,
                    isnull(sum(case DetailType
                                 when 214 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal214 ,
                    isnull(sum(case DetailType
                                 when 215 then Qty
                                 else 0
                               end), 0) as Qty215 ,
                    isnull(sum(case DetailType
                                 when 215 then CostTotal
                                 else 0
                               end), 0) as Total215 ,
                    isnull(sum(case DetailType
                                 when 215 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal215 ,
                    isnull(sum(case DetailType
                                 when 216 then Qty
                                 else 0
                               end), 0) as Qty216 ,
                    isnull(sum(case DetailType
                                 when 216 then CostTotal
                                 else 0
                               end), 0) as Total216 ,
                    isnull(sum(case DetailType
                                 when 216 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal216 ,
                    isnull(sum(case DetailType
                                 when 218 then Qty
                                 else 0
                               end), 0) as Qty218 ,
                    isnull(sum(case DetailType
                                 when 218 then CostTotal
                                 else 0
                               end), 0) as Total218 ,
                    isnull(sum(case DetailType
                                 when 218 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal218 ,
                    isnull(sum(case DetailType
                                 when 220 then Qty
                                 else 0
                               end), 0) as Qty220 ,
                    isnull(sum(case DetailType
                                 when 220 then CostTotal
                                 else 0
                               end), 0) as Total220 ,
                    isnull(sum(case DetailType
                                 when 220 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal220 ,
                    isnull(sum(case DetailType
                                 when 221 then Qty
                                 else 0
                               end), 0) as Qty221 ,
                    isnull(sum(case DetailType
                                 when 221 then CostTotal
                                 else 0
                               end), 0) as Total221 ,
                    isnull(sum(case DetailType
                                 when 221 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal221 ,
                    isnull(sum(case DetailType
                                 when 301 then Qty
                                 else 0
                               end), 0) as Qty301 ,
                    isnull(sum(case DetailType
                                 when 301 then CostTotal
                                 else 0
                               end), 0) as Total301 ,
                    isnull(sum(case DetailType
                                 when 301 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal301 ,
                    isnull(sum(case DetailType
                                 when 401 then Qty
                                 else 0
                               end), 0) as Qty401 ,
                    isnull(sum(case DetailType
                                 when 401 then CostTotal
                                 else 0
                               end), 0) as Total401 ,
                    isnull(sum(case DetailType
                                 when 401 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal401
            from    #TempAllJXC2 a --where not (DetailType = 301 and (qty = 0 or CostTotal = 0)) 
            group by PtypeId
	end                    
			
	if @Displaymode = 2 
	begin	        
				
			select PtypeId,case when (detailtype > 200 and detailtype < 300) then -SUM(Qty) else SUM(Qty) end as qty,
					case when (detailtype > 200 and detailtype < 300) then -SUM(CostTotal) else SUM(CostTotal) end as costtotal,	detailtype,ColorId,SizeId,
						CASE WHEN (detailtype > 200 and detailtype < 300) THEN -sum(RetailTotal) ELSE sum(RetailTotal) END as RetailTotal into #TempAllJXC3 from 
				(			select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,DetailType,ColorId,SizeId,ROUND(CONVERT(NUMERIC(24,10),sum(c.RetailPrice*qty)),@dig_total) as retailtotal from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				where Datadate between @DateBegin and @DateEnd
				and exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId,ColorId,SizeId,DetailType
				union all
				select PtypeId,-SUM(Qty) as qty,-SUM(CostTotal) as costtotal,	401,ColorId,SizeId,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),-Qty)*CONVERT(NUMERIC(24,10),c.RetailPrice))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				where Datadate > @DateEnd
				and 
				exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId,ColorId,SizeId,DetailType
				union all
				select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	301,ColorId,SizeId,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				where Datadate < @DateBegin
				and 
				exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId,ColorId,SizeId
				union all (select Ptypeid,SUM(d.qty) as qty,SUM(d.total) as costtotal,301 as detialtype,d.ColorId,d.SizeId,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),d.Qty))),@dig_total) as retailtotal from IniGoodsStocks a inner join IniGoodsDetail d on a.OrderId = d.OrderId
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
						where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId,ColorId,SizeId)
				union all (select Ptypeid,SUM(d.qty) as qty,SUM(d.total) as costtotal,401 as detialtype,d.ColorId,d.SizeId,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),d.Qty))),@dig_total) as retailtotal from GoodsStocks a inner join Goodsstockdetail d on a.OrderId = d.OrderId
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
						where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId,ColorId,SizeId)							
				) a
				group by PtypeId,DetailType,colorid,sizeid
				
				
            select  PtypeId ,
                    Right('00000' + cast(colorid as varchar),5) as pctypeid ,
                    Right('00000' + cast(sizeid as varchar),5) as pstypeid ,
		    --(SELECT TOP 1 [Order] FROM [dbo].[Size] si WHERE right('00000' + CAST(si.SizeId as VARCHAR), 5)  = pstypeid ) AS psOrder , 
                    isnull(sum(case DetailType
                                 when 101 then Qty
                                 else 0
                               end), 0) as Qty101 ,
                    isnull(sum(case DetailType
                                 when 101 then CostTotal
                                 else 0
                               end), 0) as Total101 ,
                    isnull(sum(case DetailType
                                 when 101 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal101 ,
                    isnull(sum(case DetailType
                                 when 102 then Qty
                                 else 0
                               end), 0) as Qty102 ,
                    isnull(sum(case DetailType
                                 when 102 then CostTotal
                                 else 0
                               end), 0) as Total102 ,
                    isnull(sum(case DetailType
                                 when 102 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal102 ,
                    isnull(sum(case DetailType
                                 when 103 then Qty
                                 else 0
                               end), 0) as Qty103 ,
                    isnull(sum(case DetailType
                                 when 103 then CostTotal
                                 else 0
                               end), 0) as Total103 ,
                    isnull(sum(case DetailType
                                 when 103 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal103 ,
                    isnull(sum(case DetailType
                                 when 104 then Qty
                                 else 0
                               end), 0) as Qty104 ,
                    isnull(sum(case DetailType
                                 when 104 then CostTotal
                                 else 0
                               end), 0) as Total104 ,
                    isnull(sum(case DetailType
                                 when 104 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal104 ,
                    isnull(sum(case DetailType
                                 when 105 then Qty
                                 else 0
                               end), 0) as Qty105 ,
                    isnull(sum(case DetailType
                                 when 105 then CostTotal
                                 else 0
                               end), 0) as Total105 ,
                    isnull(sum(case DetailType
                                 when 105 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal105 ,
                    isnull(sum(case DetailType
                                 when 106 then Qty
                                 else 0
                               end), 0) as Qty106 ,
                    isnull(sum(case DetailType
                                 when 106 then CostTotal
                                 else 0
                               end), 0) as Total106 ,
                    isnull(sum(case DetailType
                                 when 106 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal106 ,
                    isnull(sum(case DetailType
                                 when 107 then Qty
                                 else 0
                               end), 0) as Qty107 ,
                    isnull(sum(case DetailType
                                 when 107 then CostTotal
                                 else 0
                               end), 0) as Total107 ,
                    isnull(sum(case DetailType
                                 when 107 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal107 ,
                    isnull(sum(case DetailType
                                 when 108 then Qty
                                 else 0
                               end), 0) as Qty108 ,
                    isnull(sum(case DetailType
                                 when 108 then CostTotal
                                 else 0
                               end), 0) as Total108 ,
                    isnull(sum(case DetailType
                                 when 108 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal108 ,
                    isnull(sum(case DetailType
                                 when 109 then Qty
                                 else 0
                               end), 0) as Qty109 ,
                    isnull(sum(case DetailType
                                 when 109 then CostTotal
                                 else 0
                               end), 0) as Total109 ,
                    isnull(sum(case DetailType
                                 when 109 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal109 ,
                    isnull(sum(case DetailType
                                 when 110 then Qty
                                 else 0
                               end), 0) as Qty110 ,
                    isnull(sum(case DetailType
                                 when 110 then CostTotal
                                 else 0
                               end), 0) as Total110 ,
                    isnull(sum(case DetailType
                                 when 110 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal110 ,
                    isnull(sum(case DetailType
                                 when 112 then Qty
                                 else 0
                               end), 0) as Qty112 ,
                    isnull(sum(case DetailType
                                 when 112 then CostTotal
                                 else 0
                               end), 0) as Total112 ,
                    isnull(sum(case DetailType
                                 when 112 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal112 ,
                    isnull(sum(case DetailType
                                 when 113 then Qty
                                 else 0
                               end), 0) as Qty113 ,
                    isnull(sum(case DetailType
                                 when 113 then CostTotal
                                 else 0
                               end), 0) as Total113 ,
                    isnull(sum(case DetailType
                                 when 113 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal113 ,
                    isnull(sum(case DetailType
                                 when 114 then Qty
                                 else 0
                               end), 0) as Qty114 ,
                    isnull(sum(case DetailType
                                 when 114 then CostTotal
                                 else 0
                               end), 0) as Total114 ,
                    isnull(sum(case DetailType
                                 when 114 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal114 ,
                    isnull(sum(case DetailType
                                 when 115 then Qty
                                 else 0
                               end), 0) as Qty115 ,
                    isnull(sum(case DetailType
                                 when 115 then CostTotal
                                 else 0
                               end), 0) as Total115 ,
                    isnull(sum(case DetailType
                                 when 115 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal115 ,
                    isnull(sum(case DetailType
                                 when 116 then Qty
                                 else 0
                               end), 0) as Qty116 ,
                    isnull(sum(case DetailType
                                 when 116 then CostTotal
                                 else 0
                               end), 0) as Total116 ,
                    isnull(sum(case DetailType
                                 when 116 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal116 ,
                    isnull(sum(case DetailType
                                 when 118 then Qty
                                 else 0
                               end), 0) as Qty118 ,
                    isnull(sum(case DetailType
                                 when 118 then CostTotal
                                 else 0
                               end), 0) as Total118 ,
                    isnull(sum(case DetailType
                                 when 118 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal118 ,
                    isnull(sum(case DetailType
                                 when 120 then Qty
                                 else 0
                               end), 0) as Qty120 ,
                    isnull(sum(case DetailType
                                 when 120 then CostTotal
                                 else 0
                               end), 0) as Total120 ,
                    isnull(sum(case DetailType
                                 when 120 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal120 ,
                    isnull(sum(case DetailType
                                 when 121 then Qty
                                 else 0
                               end), 0) as Qty121 ,
                    isnull(sum(case DetailType
                                 when 121 then CostTotal
                                 else 0
                               end), 0) as Total121 ,
                    isnull(sum(case DetailType
                                 when 121 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal121 ,
                    isnull(sum(case DetailType
                                 when 201 then Qty
                                 else 0
                               end), 0) as Qty201 ,
                    isnull(sum(case DetailType
                                 when 201 then CostTotal
                                 else 0
                               end), 0) as Total201 ,
                    isnull(sum(case DetailType
                                 when 201 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal201 ,
                    isnull(sum(case DetailType
                                 when 202 then Qty
                                 else 0
                               end), 0) as Qty202 ,
                    isnull(sum(case DetailType
                                 when 202 then CostTotal
                                 else 0
                               end), 0) as Total202 ,
                    isnull(sum(case DetailType
                                 when 202 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal202 ,
                    isnull(sum(case DetailType
                                 when 203 then Qty
                                 else 0
                               end), 0) as Qty203 ,
                    isnull(sum(case DetailType
                                 when 203 then CostTotal
                                 else 0
                               end), 0) as Total203 ,
                    isnull(sum(case DetailType
                                 when 203 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal203 ,
                    isnull(sum(case DetailType
                                 when 204 then Qty
                                 else 0
                               end), 0) as Qty204 ,
                    isnull(sum(case DetailType
                                 when 204 then CostTotal
                                 else 0
                               end), 0) as Total204 ,
                    isnull(sum(case DetailType
                                 when 204 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal204 ,
                    isnull(sum(case DetailType
                                 when 205 then Qty
                                 else 0
                               end), 0) as Qty205 ,
                    isnull(sum(case DetailType
                                 when 205 then CostTotal
                                 else 0
                               end), 0) as Total205 ,
                    isnull(sum(case DetailType
                                 when 205 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal205 ,
                    isnull(sum(case DetailType
                                 when 206 then Qty
                                 else 0
                               end), 0) as Qty206 ,
                    isnull(sum(case DetailType
                                 when 206 then CostTotal
                                 else 0
                               end), 0) as Total206 ,
                    isnull(sum(case DetailType
                                 when 206 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal206 ,
                    isnull(sum(case DetailType
                                 when 207 then Qty
                                 else 0
                               end), 0) as Qty207 ,
                    isnull(sum(case DetailType
                                 when 207 then CostTotal
                                 else 0
                               end), 0) as Total207 ,
                    isnull(sum(case DetailType
                                 when 207 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal207 ,
                    isnull(sum(case DetailType
                                 when 208 then Qty
                                 else 0
                               end), 0) as Qty208 ,
                    isnull(sum(case DetailType
                                 when 208 then CostTotal
                                 else 0
                               end), 0) as Total208 ,
                    isnull(sum(case DetailType
                                 when 208 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal208 ,
                    isnull(sum(case DetailType
                                 when 209 then Qty
                                 else 0
                               end), 0) as Qty209 ,
                    isnull(sum(case DetailType
                                 when 209 then CostTotal
                                 else 0
                               end), 0) as Total209 ,
                    isnull(sum(case DetailType
                                 when 209 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal209 ,
                    isnull(sum(case DetailType
                                 when 210 then Qty
                                 else 0
                               end), 0) as Qty210 ,
                    isnull(sum(case DetailType
                                 when 210 then CostTotal
                                 else 0
                               end), 0) as Total210 ,
                    isnull(sum(case DetailType
                                 when 210 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal210 ,
                    isnull(sum(case DetailType
                                 when 212 then Qty
                                 else 0
                               end), 0) as Qty212 ,
                    isnull(sum(case DetailType
                                 when 212 then CostTotal
                                 else 0
                               end), 0) as Total212 ,
                    isnull(sum(case DetailType
                                 when 212 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal212 ,
                    isnull(sum(case DetailType
                                 when 213 then Qty
                                 else 0
                               end), 0) as Qty213 ,
                    isnull(sum(case DetailType
                                 when 213 then CostTotal
                                 else 0
                               end), 0) as Total213 ,
                    isnull(sum(case DetailType
                                 when 213 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal213 ,
                    isnull(sum(case DetailType
                                 when 214 then Qty
                                 else 0
                               end), 0) as Qty214 ,
                    isnull(sum(case DetailType
                                 when 214 then CostTotal
                                 else 0
                               end), 0) as Total214 ,
                    isnull(sum(case DetailType
                                 when 214 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal214 ,
                    isnull(sum(case DetailType
                                 when 215 then Qty
                                 else 0
                               end), 0) as Qty215 ,
                    isnull(sum(case DetailType
                                 when 215 then CostTotal
                                 else 0
                               end), 0) as Total215 ,
                    isnull(sum(case DetailType
                                 when 215 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal215 ,
                    isnull(sum(case DetailType
                                 when 216 then Qty
                                 else 0
                               end), 0) as Qty216 ,
                    isnull(sum(case DetailType
                                 when 216 then CostTotal
                                 else 0
                               end), 0) as Total216 ,
                    isnull(sum(case DetailType
                                 when 216 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal216 ,
                    isnull(sum(case DetailType
                                 when 218 then Qty
                                 else 0
                               end), 0) as Qty218 ,
                    isnull(sum(case DetailType
                                 when 218 then CostTotal
                                 else 0
                               end), 0) as Total218 ,
                    isnull(sum(case DetailType
                                 when 218 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal218 ,
                    isnull(sum(case DetailType
                                 when 220 then Qty
                                 else 0
                               end), 0) as Qty220 ,
                    isnull(sum(case DetailType
                                 when 220 then CostTotal
                                 else 0
                               end), 0) as Total220 ,
                    isnull(sum(case DetailType
                                 when 220 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal220 ,
                    isnull(sum(case DetailType
                                 when 221 then Qty
                                 else 0
                               end), 0) as Qty221 ,
                    isnull(sum(case DetailType
                                 when 221 then CostTotal
                                 else 0
                               end), 0) as Total221 ,
                    isnull(sum(case DetailType
                                 when 221 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal221 ,
                    isnull(sum(case DetailType
                                 when 301 then Qty
                                 else 0
                               end), 0) as Qty301 ,
                    isnull(sum(case DetailType
                                 when 301 then CostTotal
                                 else 0
                               end), 0) as Total301 ,
                    isnull(sum(case DetailType
                                 when 301 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal301 ,
                    isnull(sum(case DetailType
                                 when 401 then Qty
                                 else 0
                               end), 0) as Qty401 ,
                    isnull(sum(case DetailType
                                 when 401 then CostTotal
                                 else 0
                               end), 0) as Total401 ,
                    isnull(sum(case DetailType
                                 when 401 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal401
            from    #TempAllJXC3 a --where not (DetailType = 301 and (qty = 0 or CostTotal = 0)) 
		
            group by PtypeId ,
                    ColorId ,
                    SizeId	
	end                    
    if object_id('tempdb..#AllJXCKtypeIdTable') is not null 
        drop table #AllJXCKtypeIdTable
    if object_id('tempdb..#AllJXCPtypeIdTable') is not null 
        drop table #AllJXCPtypeIdTable        
    if object_id('tempdb..#TempAllJXC1') is not null 
        drop table #TempAllJXC1       
    if object_id('tempdb..#TempAllJXC2') is not null 
        drop table #TempAllJXC2       
    if object_id('tempdb..#TempAllJXC2q') is not null 
        drop table #TempAllJXC2q                      
    if object_id('tempdb..#TempAllJXC3') is not null 
        drop table #TempAllJXC3                               
        
end                            




GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


--  ********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：F_S_GetUser                                                 
--  ||   过程功能：系统设置－－用户设置（读）  
--  ||=========================================================================================  
--  ||   参数说明：  参数名称         类型            意义                     输入输出  
--  ||            -----------------------------------------------------------------------------  
--  ||        @cMode             int         1:录帐配置，2:查帐配置，3:其它配置  
--  ||          
--  ||=========================================================================================     
--  ||   返回值：         值                                     说明  
--  ||       ----------------------------------------------------------------------------------------  
--  ||      
--  ||==========================================================================================  
CREATE PROCEDURE FZGetUser  
(
	@cMode	int   
)  
AS  

--113 系统允许可发货库存为负库存 此配置默认为允许，不显示出来

if @cMode = 1
  select [order],[name],[stats] From syscon Where number =@cmode and [order] not IN (2,3,5,21,103,108,115,113) order by [order]   
ELSE IF @cMode = 2
  select [order],[name],[stats] From syscon Where number =@cmode and [order] not in (2,3,5,21,103,108,115,113,37,70,105) order by [order]
ELSE IF @cMode = 3
  select [order],[name],[stats] From syscon WHERE Number IN (1,2,3) AND [order] IN (13,14,22,33,36,70,81,82,89,104,107,109,111,114,140,141,142,143,144,145,146,240,250,252) ORDER BY [name]

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/****** Object:  StoredProcedure [dbo].[FzGetAllPowerPro]    Script Date: 03/13/2012 16:01:35 ******/
IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[FZGetAllJXC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].FZGetAllJXC
GO


/****** Object:  StoredProcedure [dbo].[FZGetAllJXC]    Script Date: 03/13/2012 16:01:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].FZGetAllJXC
(
      @BranchId varchar(8000) ,
      @PtypeId varchar(50) ,
      @KtypeId varchar(8000) ,
      @DateBegin varchar(15) ,
      @DateEnd varchar(15) ,
      @Displaymode int ,
      @OperatorId VARCHAR(50),
      @OnlyCheckChange bit = 0
)
as
begin

	Declare @NdxMaxId int
	Declare @QryMaxId int
	select @NdxMaxId = MAX(vchcode) from dlyndx
	select @QryMaxId = cast(subvalue as int) from QueryVchcodeRec where subname = 'AllPowerMaxVch'
	--新增存储过程 GetDig，用来取小数配置。以后所有报表存储过程对小数位的取舍用以下方式。
    DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
    EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
	
	if (@NdxMaxId > @QryMaxId) or exists(select 1 from TBAllPowerChangeVchcode where vchcode <= @QryMaxId)
	begin
	        if object_id('tempdb..#InoutVchTypeTemp') is not null 
	        	drop table #InoutVchTypeTemp
		Delete from TBAllPowerChangeVchcode where vchcode > @QryMaxId		
		Create Table #InoutVchTypeTemp
		(
		 VchType int,
		 DetailType int,
		 Phid int
		)
			insert into #InoutVchTypeTemp select vchtype,detailtype,phid from 
			(Select 34 as vchtype,101 as detailtype,0 as phid union all
			Select 45 as vchtype,102 as detailtype,0 as phid union all
			Select 101 as vchtype,102 as detailtype,0 as phid union all
			Select 16 as vchtype,103 as detailtype,0 as phid union all
			Select 14 as vchtype,104 as detailtype,0 as phid union all		
			Select 126 as vchtype,105 as detailtype,0 as phid union all
			Select 17 as vchtype,106 as detailtype,0 as phid union all
			Select 21 as vchtype,107 as detailtype,0 as phid union all
			Select 24 as vchtype,108 as detailtype,0 as phid union all
			Select 57 as vchtype,109 as detailtype,0 as phid union all
			Select 13 as vchtype,112 as detailtype,0 as phid union all
			Select 101 as vchtype,112 as detailtype,0 as phid union all
			Select 100 as vchtype,112 as detailtype,0 as phid union all
			Select 12 as vchtype,112 as detailtype,0 as phid union all
			Select 212 as vchtype,113 as detailtype,1 as phid union all
			Select 218 as vchtype,113 as detailtype,1 as phid union all
			Select 212 as vchtype,113 as detailtype,3 as phid union all
			Select 218 as vchtype,113 as detailtype,3 as phid union all
			Select 224 as vchtype,115 as detailtype,0 as phid union all
			Select 230 as vchtype,116 as detailtype,0 as phid union all
			Select 212 as vchtype,118 as detailtype,2 as phid union all
			Select 218 as vchtype,118 as detailtype,2 as phid union all
			Select 150 as vchtype,120 as detailtype,0 as phid union all
			Select 252 as vchtype,121 as detailtype,0 as phid union all
			Select 11 as vchtype,201 as detailtype,0 as phid union all
			Select 6 as vchtype,202 as detailtype,0 as phid union all
			Select 16 as vchtype,203 as detailtype,0 as phid union all
			Select 139 as vchtype,204 as detailtype,0 as phid union all
			Select 17 as vchtype,205 as detailtype,0 as phid union all
			Select 9 as vchtype,206 as detailtype,0 as phid union all
			Select 21 as vchtype,207 as detailtype,0 as phid union all
			Select 24 as vchtype,208 as detailtype,0 as phid union all
			Select 57 as vchtype,209 as detailtype,0 as phid union all
			Select 13 as vchtype,212 as detailtype,0 as phid union all
			Select 101 as vchtype,212 as detailtype,0 as phid union all
			Select 100 as vchtype,212 as detailtype,0 as phid union all
			Select 12 as vchtype,212 as detailtype,0 as phid union all
			Select 212 as vchtype,213 as detailtype,1 as phid union all
			Select 212 as vchtype,213 as detailtype,3 as phid union all
			Select 218 as vchtype,213 as detailtype,1 as phid union all
			Select 218 as vchtype,213 as detailtype,3 as phid union all
			Select 222 as vchtype,215 as detailtype,0 as phid union all
			Select 224 as vchtype,215 as detailtype,0 as phid union all
			Select 230 as vchtype,216 as detailtype,0 as phid union all
			Select 212 as vchtype,218 as detailtype,2 as phid union all
			Select 218 as vchtype,218 as detailtype,2 as phid union all
			Select 150 as vchtype,220 as detailtype,0 as phid union all
			Select 251 as vchtype,221 as detailtype,0 as phid
			) a	

		Insert into TableForAllJXC select a.phid,b.PtypeId,c.ColorID,c.SizeID,b.BranchId,b.ktypeId,CONVERT(NUMERIC(24,10),sum(c.Qty)),CONVERT(NUMERIC(24,10),sum(c.CostTotal)),
		           CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (b.Usedtype='2' OR (b.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,a.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,a.AccountTime, 23 ) ELSE a.[date] END,
		           x.DetailType
		From DlyNdx a inner join DlyData b on a.Vchcode = b.Vchcode inner join dlydatadetail c on b.DlyOrder = c.DlyOrder --inner join #AllJXCKtypeIdTable f on b.KtypeId = f.KtypeId
			  Inner join #InoutVchTypeTemp x on a.Vchtype = x.VchType and x.Phid = a.PhId 
				--由于红冲单据的存在 所以出入库不能用正负号判断，故去掉
			 AND  
			 (
				(
					(
						(( c.qty > 0) and x.DetailType < 200) 
						OR  
						(( c.qty < 0) and x.DetailType > 200)
					) 
					AND a.RedWord = 'F'
				)
				OR
				(
					(
						(( c.qty > 0) and x.DetailType > 200) 
						OR  
						(( c.qty < 0) and x.DetailType < 200)
					) 
					AND a.RedWord = 'T'
				)
			)
			and ((b.Vchcode > @QryMaxId) or (b.vchcode in (select vchcode from TBAllPowerChangeVchcode) and ((b.ktypeid = '99999' and b.Qty < 0) or b.usedtype = 2)))
			----将新增单据数据以及验收的老单据数据写入表中
		group by a.phid,b.PtypeId,c.ColorID,c.SizeID ,b.BranchId,b.ktypeId ,CASE WHEN (a.VchType IN (224,232) OR (a.Vchtype IN (212,218) AND (b.Usedtype='2' OR (b.Usedtype='3' AND b.Qty<0)))) THEN CONVERT(varchar(12) ,a.checkdate, 23 ) WHEN a.Vchtype = 230 THEN CONVERT(varchar(12) ,a.AccountTime, 23 ) ELSE a.[date] END,x.DetailType
		drop table #InoutVchTypeTemp
		Update QueryVchcodeRec set subvalue = cast(@NdxMaxId as varchar) where subname = 'AllPowerMaxVch'		
		Delete from TBAllPowerChangeVchcode where vchcode <= @QryMaxId		
	end
		
    if object_id('tempdb..#AllJXCKtypeIdTable') is not null 
        drop table #AllJXCKtypeIdTable
    if object_id('tempdb..#AllJXCPtypeIdTable') is not null 
        drop table #AllJXCPtypeIdTable        
        
    select  KtypeId
    Into    #AllJXCKtypeIdTable
    from    FN_GetStockListOfBranch(@OperatorID, @BranchId, @Ktypeid) a
    where   exists ( select 1
                     from   Stock b
                     where  a.ktypeid = b.typeid
                            and b.branchtype <> 4 )
	create CLUSTERED index TempIdx1 on #AllJXCKtypeIdTable(Ktypeid)                             

	Select typeId,retailPrice
	Into #AllJXCPtypeIdTable
	from FN_GetPowerRangePList(@OperatorId, @PtypeId) a
        where @OnlyCheckChange = 0 or (@OnlyCheckChange = 1 and exists (Select 1 from TableForAllJXC x where Datadate between @DateBegin and @DateEnd and a.typeId = x.PtypeId)) 
	
	create CLUSTERED index TempIdx2 on #AllJXCPtypeIdTable(typeId)                    
	
    if @DisplayMode = 0 
        begin
			select Ptypeid,case when (detailtype > 200 and detailtype < 300) then -SUM(Qty) else SUM(Qty) end as qty,
				case when (detailtype > 200 and detailtype < 300) then -SUM(CostTotal) else SUM(CostTotal) end as costtotal,	detailtype,
						CASE WHEN (detailtype > 200 and detailtype < 300) THEN -sum(RetailTotal) ELSE sum(RetailTotal) END as RetailTotal into #TempAllJXC1 from 
				(select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	detailtype,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as RetailTotal from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate between @DateBegin and @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,Left(PtypeId, Len(@PtypeId) + 5)
				union all
				select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,-SUM(Qty) as qty,-SUM(CostTotal) as costtotal,	401,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),-Qty)*CONVERT(NUMERIC(24,10),c.RetailPrice))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate > @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,Left(PtypeId, Len(@PtypeId) + 5) 
				union all
				select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	301,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate < @DateBegin
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by Left(PtypeId, Len(@PtypeId) + 5)
				union all (select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(qty) as qty,SUM(total) as costtotal,301 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from IniGoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by Left(PtypeId, Len(@PtypeId) + 5))
				union all (select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(qty) as qty,SUM(total) as costtotal,401 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from GoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by Left(PtypeId, Len(@PtypeId) + 5))						
				) a
				group by PtypeId,DetailType



				
            select  PtypeId ,
                                      isnull(sum(case DetailType
                                 when 101 then Qty
                                 else 0
                               end), 0) as Qty101 ,
                    isnull(sum(case DetailType
                                 when 101 then CostTotal
                                 else 0
                               end), 0) as Total101 ,
                    isnull(sum(case DetailType
                                 when 101 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal101 ,
                    isnull(sum(case DetailType
                                 when 102 then Qty
                                 else 0
                               end), 0) as Qty102 ,
                    isnull(sum(case DetailType
                                 when 102 then CostTotal
                                 else 0
                               end), 0) as Total102 ,
                    isnull(sum(case DetailType
                                 when 102 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal102 ,
                    isnull(sum(case DetailType
                                 when 103 then Qty
                                 else 0
                               end), 0) as Qty103 ,
                    isnull(sum(case DetailType
                                 when 103 then CostTotal
                                 else 0
                               end), 0) as Total103 ,
                    isnull(sum(case DetailType
                                 when 103 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal103 ,
                    isnull(sum(case DetailType
                                 when 104 then Qty
                                 else 0
                               end), 0) as Qty104 ,
                    isnull(sum(case DetailType
                                 when 104 then CostTotal
                                 else 0
                               end), 0) as Total104 ,
                    isnull(sum(case DetailType
                                 when 104 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal104 ,
                    isnull(sum(case DetailType
                                 when 105 then Qty
                                 else 0
                               end), 0) as Qty105 ,
                    isnull(sum(case DetailType
                                 when 105 then CostTotal
                                 else 0
                               end), 0) as Total105 ,
                    isnull(sum(case DetailType
                                 when 105 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal105 ,
                    isnull(sum(case DetailType
                                 when 106 then Qty
                                 else 0
                               end), 0) as Qty106 ,
                    isnull(sum(case DetailType
                                 when 106 then CostTotal
                                 else 0
                               end), 0) as Total106 ,
                    isnull(sum(case DetailType
                                 when 106 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal106 ,
                    isnull(sum(case DetailType
                                 when 107 then Qty
                                 else 0
                               end), 0) as Qty107 ,
                    isnull(sum(case DetailType
                                 when 107 then CostTotal
                                 else 0
                               end), 0) as Total107 ,
                    isnull(sum(case DetailType
                                 when 107 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal107 ,
                    isnull(sum(case DetailType
                                 when 108 then Qty
                                 else 0
                               end), 0) as Qty108 ,
                    isnull(sum(case DetailType
                                 when 108 then CostTotal
                                 else 0
                               end), 0) as Total108 ,
                    isnull(sum(case DetailType
                                 when 108 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal108 ,
                    isnull(sum(case DetailType
                                 when 109 then Qty
                                 else 0
                               end), 0) as Qty109 ,
                    isnull(sum(case DetailType
                                 when 109 then CostTotal
                                 else 0
                               end), 0) as Total109 ,
                    isnull(sum(case DetailType
                                 when 109 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal109 ,
                    isnull(sum(case DetailType
                                 when 110 then Qty
                                 else 0
                               end), 0) as Qty110 ,
                    isnull(sum(case DetailType
                                 when 110 then CostTotal
                                 else 0
                               end), 0) as Total110 ,
                    isnull(sum(case DetailType
                                 when 110 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal110 ,
                    isnull(sum(case DetailType
                                 when 112 then Qty
                                 else 0
                               end), 0) as Qty112 ,
                    isnull(sum(case DetailType
                                 when 112 then CostTotal
                                 else 0
                               end), 0) as Total112 ,
                    isnull(sum(case DetailType
                                 when 112 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal112 ,
                    isnull(sum(case DetailType
                                 when 113 then Qty
                                 else 0
                               end), 0) as Qty113 ,
                    isnull(sum(case DetailType
                                 when 113 then CostTotal
                                 else 0
                               end), 0) as Total113 ,
                    isnull(sum(case DetailType
                                 when 113 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal113 ,
                    isnull(sum(case DetailType
                                 when 114 then Qty
                                 else 0
                               end), 0) as Qty114 ,
                    isnull(sum(case DetailType
                                 when 114 then CostTotal
                                 else 0
                               end), 0) as Total114 ,
                    isnull(sum(case DetailType
                                 when 114 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal114 ,
                    isnull(sum(case DetailType
                                 when 115 then Qty
                                 else 0
                               end), 0) as Qty115 ,
                    isnull(sum(case DetailType
                                 when 115 then CostTotal
                                 else 0
                               end), 0) as Total115 ,
                    isnull(sum(case DetailType
                                 when 115 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal115 ,
                    isnull(sum(case DetailType
                                 when 116 then Qty
                                 else 0
                               end), 0) as Qty116 ,
                    isnull(sum(case DetailType
                                 when 116 then CostTotal
                                 else 0
                               end), 0) as Total116 ,
                    isnull(sum(case DetailType
                                 when 116 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal116 ,
                    isnull(sum(case DetailType
                                 when 118 then Qty
                                 else 0
                               end), 0) as Qty118 ,
                    isnull(sum(case DetailType
                                 when 118 then CostTotal
                                 else 0
                               end), 0) as Total118 ,
                    isnull(sum(case DetailType
                                 when 118 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal118 ,
                    isnull(sum(case DetailType
                                 when 120 then Qty
                                 else 0
                               end), 0) as Qty120 ,
                    isnull(sum(case DetailType
                                 when 120 then CostTotal
                                 else 0
                               end), 0) as Total120 ,
                    isnull(sum(case DetailType
                                 when 120 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal120 ,
                    isnull(sum(case DetailType
                                 when 121 then Qty
                                 else 0
                               end), 0) as Qty121 ,
                    isnull(sum(case DetailType
                                 when 121 then CostTotal
                                 else 0
                               end), 0) as Total121 ,
                    isnull(sum(case DetailType
                                 when 121 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal121 ,
                    isnull(sum(case DetailType
                                 when 201 then Qty
                                 else 0
                               end), 0) as Qty201 ,
                    isnull(sum(case DetailType
                                 when 201 then CostTotal
                                 else 0
                               end), 0) as Total201 ,
                    isnull(sum(case DetailType
                                 when 201 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal201 ,
                    isnull(sum(case DetailType
                                 when 202 then Qty
                                 else 0
                               end), 0) as Qty202 ,
                    isnull(sum(case DetailType
                                 when 202 then CostTotal
                                 else 0
                               end), 0) as Total202 ,
                    isnull(sum(case DetailType
                                 when 202 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal202 ,
                    isnull(sum(case DetailType
                                 when 203 then Qty
                                 else 0
                               end), 0) as Qty203 ,
                    isnull(sum(case DetailType
                                 when 203 then CostTotal
                                 else 0
                               end), 0) as Total203 ,
                    isnull(sum(case DetailType
                                 when 203 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal203 ,
                    isnull(sum(case DetailType
                                 when 204 then Qty
                                 else 0
                               end), 0) as Qty204 ,
                    isnull(sum(case DetailType
                                 when 204 then CostTotal
                                 else 0
                               end), 0) as Total204 ,
                    isnull(sum(case DetailType
                                 when 204 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal204 ,
                    isnull(sum(case DetailType
                                 when 205 then Qty
                                 else 0
                               end), 0) as Qty205 ,
                    isnull(sum(case DetailType
                                 when 205 then CostTotal
                                 else 0
                               end), 0) as Total205 ,
                    isnull(sum(case DetailType
                                 when 205 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal205 ,
                    isnull(sum(case DetailType
                                 when 206 then Qty
                                 else 0
                               end), 0) as Qty206 ,
                    isnull(sum(case DetailType
                                 when 206 then CostTotal
                                 else 0
                               end), 0) as Total206 ,
                    isnull(sum(case DetailType
                                 when 206 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal206 ,
                    isnull(sum(case DetailType
                                 when 207 then Qty
                                 else 0
                               end), 0) as Qty207 ,
                    isnull(sum(case DetailType
                                 when 207 then CostTotal
                                 else 0
                               end), 0) as Total207 ,
                    isnull(sum(case DetailType
                                 when 207 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal207 ,
                    isnull(sum(case DetailType
                                 when 208 then Qty
                                 else 0
                               end), 0) as Qty208 ,
                    isnull(sum(case DetailType
                                 when 208 then CostTotal
                                 else 0
                               end), 0) as Total208 ,
                    isnull(sum(case DetailType
                                 when 208 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal208 ,
                    isnull(sum(case DetailType
                                 when 209 then Qty
                                 else 0
                               end), 0) as Qty209 ,
                    isnull(sum(case DetailType
                                 when 209 then CostTotal
                                 else 0
                               end), 0) as Total209 ,
                    isnull(sum(case DetailType
                                 when 209 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal209 ,
                    isnull(sum(case DetailType
                                 when 210 then Qty
                                 else 0
                               end), 0) as Qty210 ,
                    isnull(sum(case DetailType
                                 when 210 then CostTotal
                                 else 0
                               end), 0) as Total210 ,
                    isnull(sum(case DetailType
                                 when 210 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal210 ,
                    isnull(sum(case DetailType
                                 when 212 then Qty
                                 else 0
                               end), 0) as Qty212 ,
                    isnull(sum(case DetailType
                                 when 212 then CostTotal
                                 else 0
                               end), 0) as Total212 ,
                    isnull(sum(case DetailType
                                 when 212 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal212 ,
                    isnull(sum(case DetailType
                                 when 213 then Qty
                                 else 0
                               end), 0) as Qty213 ,
                    isnull(sum(case DetailType
                                 when 213 then CostTotal
                                 else 0
                               end), 0) as Total213 ,
                    isnull(sum(case DetailType
                                 when 213 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal213 ,
                    isnull(sum(case DetailType
                                 when 214 then Qty
                                 else 0
                               end), 0) as Qty214 ,
                    isnull(sum(case DetailType
                                 when 214 then CostTotal
                                 else 0
                               end), 0) as Total214 ,
                    isnull(sum(case DetailType
                                 when 214 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal214 ,
                    isnull(sum(case DetailType
                                 when 215 then Qty
                                 else 0
                               end), 0) as Qty215 ,
                    isnull(sum(case DetailType
                                 when 215 then CostTotal
                                 else 0
                               end), 0) as Total215 ,
                    isnull(sum(case DetailType
                                 when 215 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal215 ,
                    isnull(sum(case DetailType
                                 when 216 then Qty
                                 else 0
                               end), 0) as Qty216 ,
                    isnull(sum(case DetailType
                                 when 216 then CostTotal
                                 else 0
                               end), 0) as Total216 ,
                    isnull(sum(case DetailType
                                 when 216 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal216 ,
                    isnull(sum(case DetailType
                                 when 218 then Qty
                                 else 0
                               end), 0) as Qty218 ,
                    isnull(sum(case DetailType
                                 when 218 then CostTotal
                                 else 0
                               end), 0) as Total218 ,
                    isnull(sum(case DetailType
                                 when 218 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal218 ,
                    isnull(sum(case DetailType
                                 when 220 then Qty
                                 else 0
                               end), 0) as Qty220 ,
                    isnull(sum(case DetailType
                                 when 220 then CostTotal
                                 else 0
                               end), 0) as Total220 ,
                    isnull(sum(case DetailType
                                 when 220 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal220 ,
                    isnull(sum(case DetailType
                                 when 221 then Qty
                                 else 0
                               end), 0) as Qty221 ,
                    isnull(sum(case DetailType
                                 when 221 then CostTotal
                                 else 0
                               end), 0) as Total221 ,
                    isnull(sum(case DetailType
                                 when 221 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal221 ,
                    isnull(sum(case DetailType
                                 when 301 then Qty
                                 else 0
                               end), 0) as Qty301 ,
                    isnull(sum(case DetailType
                                 when 301 then CostTotal
                                 else 0
                               end), 0) as Total301 ,
                    isnull(sum(case DetailType
                                 when 301 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal301 ,
                    isnull(sum(case DetailType
                                 when 401 then Qty
                                 else 0
                               end), 0) as Qty401 ,
                    isnull(sum(case DetailType
                                 when 401 then CostTotal
                                 else 0
                               end), 0) as Total401 ,
                    isnull(sum(case DetailType
                                 when 401 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal401
            from    #TempAllJXC1 a --where not (DetailType = 301 and (qty = 0 or CostTotal = 0)) 		
            group by PtypeId
	end                    
	
	if @Displaymode = 1 
	begin	        
			select PtypeId,case when (detailtype > 200 and detailtype < 300) then -SUM(Qty) else SUM(Qty) end as qty,
					case when (detailtype > 200 and detailtype < 300) then -SUM(CostTotal) else SUM(CostTotal) end as costtotal,	detailtype,
						CASE WHEN (detailtype > 200 and detailtype < 300) THEN -sum(RetailTotal) ELSE sum(RetailTotal) END as RetailTotal into #TempAllJXC2 from 
				(select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	detailtype,
						ROUND(CONVERT(NUMERIC(24,10),SUM(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as RetailTotal from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate between @DateBegin and @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,PtypeId
				union all
				select PtypeId,-SUM(Qty) as qty,-SUM(CostTotal) as costtotal,	401,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),-Qty)*CONVERT(NUMERIC(24,10),c.RetailPrice))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate > @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,PtypeId
				union all
				select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	301,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate < @DateBegin
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId
				union all (select Ptypeid,SUM(qty) as qty,SUM(total) as costtotal,301 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from IniGoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId)
				union all (select Ptypeid,SUM(qty) as qty,SUM(total) as costtotal,401 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from GoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId						
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId)							
				) a
				group by PtypeId,DetailType
			
				
            select  PtypeId ,
		    --(SELECT TOP 1 [Order] FROM [dbo].[Size] si WHERE right('00000' + CAST(si.SizeId as VARCHAR), 5)  = pstypeid ) AS psOrder , 
                    isnull(sum(case DetailType
                                 when 101 then Qty
                                 else 0
                               end), 0) as Qty101 ,
                    isnull(sum(case DetailType
                                 when 101 then CostTotal
                                 else 0
                               end), 0) as Total101 ,
                    isnull(sum(case DetailType
                                 when 101 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal101 ,
                    isnull(sum(case DetailType
                                 when 102 then Qty
                                 else 0
                               end), 0) as Qty102 ,
                    isnull(sum(case DetailType
                                 when 102 then CostTotal
                                 else 0
                               end), 0) as Total102 ,
                    isnull(sum(case DetailType
                                 when 102 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal102 ,
                    isnull(sum(case DetailType
                                 when 103 then Qty
                                 else 0
                               end), 0) as Qty103 ,
                    isnull(sum(case DetailType
                                 when 103 then CostTotal
                                 else 0
                               end), 0) as Total103 ,
                    isnull(sum(case DetailType
                                 when 103 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal103 ,
                    isnull(sum(case DetailType
                                 when 104 then Qty
                                 else 0
                               end), 0) as Qty104 ,
                    isnull(sum(case DetailType
                                 when 104 then CostTotal
                                 else 0
                               end), 0) as Total104 ,
                    isnull(sum(case DetailType
                                 when 104 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal104 ,
                    isnull(sum(case DetailType
                                 when 105 then Qty
                                 else 0
                               end), 0) as Qty105 ,
                    isnull(sum(case DetailType
                                 when 105 then CostTotal
                                 else 0
                               end), 0) as Total105 ,
                    isnull(sum(case DetailType
                                 when 105 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal105 ,
                    isnull(sum(case DetailType
                                 when 106 then Qty
                                 else 0
                               end), 0) as Qty106 ,
                    isnull(sum(case DetailType
                                 when 106 then CostTotal
                                 else 0
                               end), 0) as Total106 ,
                    isnull(sum(case DetailType
                                 when 106 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal106 ,
                    isnull(sum(case DetailType
                                 when 107 then Qty
                                 else 0
                               end), 0) as Qty107 ,
                    isnull(sum(case DetailType
                                 when 107 then CostTotal
                                 else 0
                               end), 0) as Total107 ,
                    isnull(sum(case DetailType
                                 when 107 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal107 ,
                    isnull(sum(case DetailType
                                 when 108 then Qty
                                 else 0
                               end), 0) as Qty108 ,
                    isnull(sum(case DetailType
                                 when 108 then CostTotal
                                 else 0
                               end), 0) as Total108 ,
                    isnull(sum(case DetailType
                                 when 108 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal108 ,
                    isnull(sum(case DetailType
                                 when 109 then Qty
                                 else 0
                               end), 0) as Qty109 ,
                    isnull(sum(case DetailType
                                 when 109 then CostTotal
                                 else 0
                               end), 0) as Total109 ,
                    isnull(sum(case DetailType
                                 when 109 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal109 ,
                    isnull(sum(case DetailType
                                 when 110 then Qty
                                 else 0
                               end), 0) as Qty110 ,
                    isnull(sum(case DetailType
                                 when 110 then CostTotal
                                 else 0
                               end), 0) as Total110 ,
                    isnull(sum(case DetailType
                                 when 110 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal110 ,
                    isnull(sum(case DetailType
                                 when 112 then Qty
                                 else 0
                               end), 0) as Qty112 ,
                    isnull(sum(case DetailType
                                 when 112 then CostTotal
                                 else 0
                               end), 0) as Total112 ,
                    isnull(sum(case DetailType
                                 when 112 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal112 ,
                    isnull(sum(case DetailType
                                 when 113 then Qty
                                 else 0
                               end), 0) as Qty113 ,
                    isnull(sum(case DetailType
                                 when 113 then CostTotal
                                 else 0
                               end), 0) as Total113 ,
                    isnull(sum(case DetailType
                                 when 113 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal113 ,
                    isnull(sum(case DetailType
                                 when 114 then Qty
                                 else 0
                               end), 0) as Qty114 ,
                    isnull(sum(case DetailType
                                 when 114 then CostTotal
                                 else 0
                               end), 0) as Total114 ,
                    isnull(sum(case DetailType
                                 when 114 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal114 ,
                    isnull(sum(case DetailType
                                 when 115 then Qty
                                 else 0
                               end), 0) as Qty115 ,
                    isnull(sum(case DetailType
                                 when 115 then CostTotal
                                 else 0
                               end), 0) as Total115 ,
                    isnull(sum(case DetailType
                                 when 115 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal115 ,
                    isnull(sum(case DetailType
                                 when 116 then Qty
                                 else 0
                               end), 0) as Qty116 ,
                    isnull(sum(case DetailType
                                 when 116 then CostTotal
                                 else 0
                               end), 0) as Total116 ,
                    isnull(sum(case DetailType
                                 when 116 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal116 ,
                    isnull(sum(case DetailType
                                 when 118 then Qty
                                 else 0
                               end), 0) as Qty118 ,
                    isnull(sum(case DetailType
                                 when 118 then CostTotal
                                 else 0
                               end), 0) as Total118 ,
                    isnull(sum(case DetailType
                                 when 118 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal118 ,
                    isnull(sum(case DetailType
                                 when 120 then Qty
                                 else 0
                               end), 0) as Qty120 ,
                    isnull(sum(case DetailType
                                 when 120 then CostTotal
                                 else 0
                               end), 0) as Total120 ,
                    isnull(sum(case DetailType
                                 when 120 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal120 ,
                    isnull(sum(case DetailType
                                 when 121 then Qty
                                 else 0
                               end), 0) as Qty121 ,
                    isnull(sum(case DetailType
                                 when 121 then CostTotal
                                 else 0
                               end), 0) as Total121 ,
                    isnull(sum(case DetailType
                                 when 121 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal121 ,
                    isnull(sum(case DetailType
                                 when 201 then Qty
                                 else 0
                               end), 0) as Qty201 ,
                    isnull(sum(case DetailType
                                 when 201 then CostTotal
                                 else 0
                               end), 0) as Total201 ,
                    isnull(sum(case DetailType
                                 when 201 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal201 ,
                    isnull(sum(case DetailType
                                 when 202 then Qty
                                 else 0
                               end), 0) as Qty202 ,
                    isnull(sum(case DetailType
                                 when 202 then CostTotal
                                 else 0
                               end), 0) as Total202 ,
                    isnull(sum(case DetailType
                                 when 202 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal202 ,
                    isnull(sum(case DetailType
                                 when 203 then Qty
                                 else 0
                               end), 0) as Qty203 ,
                    isnull(sum(case DetailType
                                 when 203 then CostTotal
                                 else 0
                               end), 0) as Total203 ,
                    isnull(sum(case DetailType
                                 when 203 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal203 ,
                    isnull(sum(case DetailType
                                 when 204 then Qty
                                 else 0
                               end), 0) as Qty204 ,
                    isnull(sum(case DetailType
                                 when 204 then CostTotal
                                 else 0
                               end), 0) as Total204 ,
                    isnull(sum(case DetailType
                                 when 204 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal204 ,
                    isnull(sum(case DetailType
                                 when 205 then Qty
                                 else 0
                               end), 0) as Qty205 ,
                    isnull(sum(case DetailType
                                 when 205 then CostTotal
                                 else 0
                               end), 0) as Total205 ,
                    isnull(sum(case DetailType
                                 when 205 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal205 ,
                    isnull(sum(case DetailType
                                 when 206 then Qty
                                 else 0
                               end), 0) as Qty206 ,
                    isnull(sum(case DetailType
                                 when 206 then CostTotal
                                 else 0
                               end), 0) as Total206 ,
                    isnull(sum(case DetailType
                                 when 206 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal206 ,
                    isnull(sum(case DetailType
                                 when 207 then Qty
                                 else 0
                               end), 0) as Qty207 ,
                    isnull(sum(case DetailType
                                 when 207 then CostTotal
                                 else 0
                               end), 0) as Total207 ,
                    isnull(sum(case DetailType
                                 when 207 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal207 ,
                    isnull(sum(case DetailType
                                 when 208 then Qty
                                 else 0
                               end), 0) as Qty208 ,
                    isnull(sum(case DetailType
                                 when 208 then CostTotal
                                 else 0
                               end), 0) as Total208 ,
                    isnull(sum(case DetailType
                                 when 208 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal208 ,
                    isnull(sum(case DetailType
                                 when 209 then Qty
                                 else 0
                               end), 0) as Qty209 ,
                    isnull(sum(case DetailType
                                 when 209 then CostTotal
                                 else 0
                               end), 0) as Total209 ,
                    isnull(sum(case DetailType
                                 when 209 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal209 ,
                    isnull(sum(case DetailType
                                 when 210 then Qty
                                 else 0
                               end), 0) as Qty210 ,
                    isnull(sum(case DetailType
                                 when 210 then CostTotal
                                 else 0
                               end), 0) as Total210 ,
                    isnull(sum(case DetailType
                                 when 210 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal210 ,
                    isnull(sum(case DetailType
                                 when 212 then Qty
                                 else 0
                               end), 0) as Qty212 ,
                    isnull(sum(case DetailType
                                 when 212 then CostTotal
                                 else 0
                               end), 0) as Total212 ,
                    isnull(sum(case DetailType
                                 when 212 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal212 ,
                    isnull(sum(case DetailType
                                 when 213 then Qty
                                 else 0
                               end), 0) as Qty213 ,
                    isnull(sum(case DetailType
                                 when 213 then CostTotal
                                 else 0
                               end), 0) as Total213 ,
                    isnull(sum(case DetailType
                                 when 213 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal213 ,
                    isnull(sum(case DetailType
                                 when 214 then Qty
                                 else 0
                               end), 0) as Qty214 ,
                    isnull(sum(case DetailType
                                 when 214 then CostTotal
                                 else 0
                               end), 0) as Total214 ,
                    isnull(sum(case DetailType
                                 when 214 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal214 ,
                    isnull(sum(case DetailType
                                 when 215 then Qty
                                 else 0
                               end), 0) as Qty215 ,
                    isnull(sum(case DetailType
                                 when 215 then CostTotal
                                 else 0
                               end), 0) as Total215 ,
                    isnull(sum(case DetailType
                                 when 215 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal215 ,
                    isnull(sum(case DetailType
                                 when 216 then Qty
                                 else 0
                               end), 0) as Qty216 ,
                    isnull(sum(case DetailType
                                 when 216 then CostTotal
                                 else 0
                               end), 0) as Total216 ,
                    isnull(sum(case DetailType
                                 when 216 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal216 ,
                    isnull(sum(case DetailType
                                 when 218 then Qty
                                 else 0
                               end), 0) as Qty218 ,
                    isnull(sum(case DetailType
                                 when 218 then CostTotal
                                 else 0
                               end), 0) as Total218 ,
                    isnull(sum(case DetailType
                                 when 218 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal218 ,
                    isnull(sum(case DetailType
                                 when 220 then Qty
                                 else 0
                               end), 0) as Qty220 ,
                    isnull(sum(case DetailType
                                 when 220 then CostTotal
                                 else 0
                               end), 0) as Total220 ,
                    isnull(sum(case DetailType
                                 when 220 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal220 ,
                    isnull(sum(case DetailType
                                 when 221 then Qty
                                 else 0
                               end), 0) as Qty221 ,
                    isnull(sum(case DetailType
                                 when 221 then CostTotal
                                 else 0
                               end), 0) as Total221 ,
                    isnull(sum(case DetailType
                                 when 221 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal221 ,
                    isnull(sum(case DetailType
                                 when 301 then Qty
                                 else 0
                               end), 0) as Qty301 ,
                    isnull(sum(case DetailType
                                 when 301 then CostTotal
                                 else 0
                               end), 0) as Total301 ,
                    isnull(sum(case DetailType
                                 when 301 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal301 ,
                    isnull(sum(case DetailType
                                 when 401 then Qty
                                 else 0
                               end), 0) as Qty401 ,
                    isnull(sum(case DetailType
                                 when 401 then CostTotal
                                 else 0
                               end), 0) as Total401 ,
                    isnull(sum(case DetailType
                                 when 401 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal401
            from    #TempAllJXC2 a --where not (DetailType = 301 and (qty = 0 or CostTotal = 0)) 
            group by PtypeId
	end                    
			
	if @Displaymode = 2 
	begin	        
				
			select PtypeId,case when (detailtype > 200 and detailtype < 300) then -SUM(Qty) else SUM(Qty) end as qty,
					case when (detailtype > 200 and detailtype < 300) then -SUM(CostTotal) else SUM(CostTotal) end as costtotal,	detailtype,ColorId,SizeId,
						CASE WHEN (detailtype > 200 and detailtype < 300) THEN -sum(RetailTotal) ELSE sum(RetailTotal) END as RetailTotal into #TempAllJXC3 from 
				(			select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,DetailType,ColorId,SizeId,ROUND(CONVERT(NUMERIC(24,10),sum(c.RetailPrice*qty)),@dig_total) as retailtotal from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				where Datadate between @DateBegin and @DateEnd
				and exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId,ColorId,SizeId,DetailType
				union all
				select PtypeId,-SUM(Qty) as qty,-SUM(CostTotal) as costtotal,	401,ColorId,SizeId,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),-Qty)*CONVERT(NUMERIC(24,10),c.RetailPrice))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				where Datadate > @DateEnd
				and 
				exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId,ColorId,SizeId,DetailType
				union all
				select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	301,ColorId,SizeId,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				where Datadate < @DateBegin
				and 
				exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId,ColorId,SizeId
				union all (select Ptypeid,SUM(d.qty) as qty,SUM(d.total) as costtotal,301 as detialtype,d.ColorId,d.SizeId,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),d.Qty))),@dig_total) as retailtotal from IniGoodsStocks a inner join IniGoodsDetail d on a.OrderId = d.OrderId
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
						where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId,ColorId,SizeId)
				union all (select Ptypeid,SUM(d.qty) as qty,SUM(d.total) as costtotal,401 as detialtype,d.ColorId,d.SizeId,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),d.Qty))),@dig_total) as retailtotal from GoodsStocks a inner join Goodsstockdetail d on a.OrderId = d.OrderId
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
						where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId,ColorId,SizeId)							
				) a
				group by PtypeId,DetailType,colorid,sizeid
				
				
            select  PtypeId ,
                    Right('00000' + cast(colorid as varchar),5) as pctypeid ,
                    Right('00000' + cast(sizeid as varchar),5) as pstypeid ,
		    --(SELECT TOP 1 [Order] FROM [dbo].[Size] si WHERE right('00000' + CAST(si.SizeId as VARCHAR), 5)  = pstypeid ) AS psOrder , 
                    isnull(sum(case DetailType
                                 when 101 then Qty
                                 else 0
                               end), 0) as Qty101 ,
                    isnull(sum(case DetailType
                                 when 101 then CostTotal
                                 else 0
                               end), 0) as Total101 ,
                    isnull(sum(case DetailType
                                 when 101 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal101 ,
                    isnull(sum(case DetailType
                                 when 102 then Qty
                                 else 0
                               end), 0) as Qty102 ,
                    isnull(sum(case DetailType
                                 when 102 then CostTotal
                                 else 0
                               end), 0) as Total102 ,
                    isnull(sum(case DetailType
                                 when 102 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal102 ,
                    isnull(sum(case DetailType
                                 when 103 then Qty
                                 else 0
                               end), 0) as Qty103 ,
                    isnull(sum(case DetailType
                                 when 103 then CostTotal
                                 else 0
                               end), 0) as Total103 ,
                    isnull(sum(case DetailType
                                 when 103 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal103 ,
                    isnull(sum(case DetailType
                                 when 104 then Qty
                                 else 0
                               end), 0) as Qty104 ,
                    isnull(sum(case DetailType
                                 when 104 then CostTotal
                                 else 0
                               end), 0) as Total104 ,
                    isnull(sum(case DetailType
                                 when 104 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal104 ,
                    isnull(sum(case DetailType
                                 when 105 then Qty
                                 else 0
                               end), 0) as Qty105 ,
                    isnull(sum(case DetailType
                                 when 105 then CostTotal
                                 else 0
                               end), 0) as Total105 ,
                    isnull(sum(case DetailType
                                 when 105 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal105 ,
                    isnull(sum(case DetailType
                                 when 106 then Qty
                                 else 0
                               end), 0) as Qty106 ,
                    isnull(sum(case DetailType
                                 when 106 then CostTotal
                                 else 0
                               end), 0) as Total106 ,
                    isnull(sum(case DetailType
                                 when 106 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal106 ,
                    isnull(sum(case DetailType
                                 when 107 then Qty
                                 else 0
                               end), 0) as Qty107 ,
                    isnull(sum(case DetailType
                                 when 107 then CostTotal
                                 else 0
                               end), 0) as Total107 ,
                    isnull(sum(case DetailType
                                 when 107 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal107 ,
                    isnull(sum(case DetailType
                                 when 108 then Qty
                                 else 0
                               end), 0) as Qty108 ,
                    isnull(sum(case DetailType
                                 when 108 then CostTotal
                                 else 0
                               end), 0) as Total108 ,
                    isnull(sum(case DetailType
                                 when 108 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal108 ,
                    isnull(sum(case DetailType
                                 when 109 then Qty
                                 else 0
                               end), 0) as Qty109 ,
                    isnull(sum(case DetailType
                                 when 109 then CostTotal
                                 else 0
                               end), 0) as Total109 ,
                    isnull(sum(case DetailType
                                 when 109 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal109 ,
                    isnull(sum(case DetailType
                                 when 110 then Qty
                                 else 0
                               end), 0) as Qty110 ,
                    isnull(sum(case DetailType
                                 when 110 then CostTotal
                                 else 0
                               end), 0) as Total110 ,
                    isnull(sum(case DetailType
                                 when 110 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal110 ,
                    isnull(sum(case DetailType
                                 when 112 then Qty
                                 else 0
                               end), 0) as Qty112 ,
                    isnull(sum(case DetailType
                                 when 112 then CostTotal
                                 else 0
                               end), 0) as Total112 ,
                    isnull(sum(case DetailType
                                 when 112 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal112 ,
                    isnull(sum(case DetailType
                                 when 113 then Qty
                                 else 0
                               end), 0) as Qty113 ,
                    isnull(sum(case DetailType
                                 when 113 then CostTotal
                                 else 0
                               end), 0) as Total113 ,
                    isnull(sum(case DetailType
                                 when 113 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal113 ,
                    isnull(sum(case DetailType
                                 when 114 then Qty
                                 else 0
                               end), 0) as Qty114 ,
                    isnull(sum(case DetailType
                                 when 114 then CostTotal
                                 else 0
                               end), 0) as Total114 ,
                    isnull(sum(case DetailType
                                 when 114 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal114 ,
                    isnull(sum(case DetailType
                                 when 115 then Qty
                                 else 0
                               end), 0) as Qty115 ,
                    isnull(sum(case DetailType
                                 when 115 then CostTotal
                                 else 0
                               end), 0) as Total115 ,
                    isnull(sum(case DetailType
                                 when 115 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal115 ,
                    isnull(sum(case DetailType
                                 when 116 then Qty
                                 else 0
                               end), 0) as Qty116 ,
                    isnull(sum(case DetailType
                                 when 116 then CostTotal
                                 else 0
                               end), 0) as Total116 ,
                    isnull(sum(case DetailType
                                 when 116 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal116 ,
                    isnull(sum(case DetailType
                                 when 118 then Qty
                                 else 0
                               end), 0) as Qty118 ,
                    isnull(sum(case DetailType
                                 when 118 then CostTotal
                                 else 0
                               end), 0) as Total118 ,
                    isnull(sum(case DetailType
                                 when 118 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal118 ,
                    isnull(sum(case DetailType
                                 when 120 then Qty
                                 else 0
                               end), 0) as Qty120 ,
                    isnull(sum(case DetailType
                                 when 120 then CostTotal
                                 else 0
                               end), 0) as Total120 ,
                    isnull(sum(case DetailType
                                 when 120 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal120 ,
                    isnull(sum(case DetailType
                                 when 121 then Qty
                                 else 0
                               end), 0) as Qty121 ,
                    isnull(sum(case DetailType
                                 when 121 then CostTotal
                                 else 0
                               end), 0) as Total121 ,
                    isnull(sum(case DetailType
                                 when 121 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal121 ,
                    isnull(sum(case DetailType
                                 when 201 then Qty
                                 else 0
                               end), 0) as Qty201 ,
                    isnull(sum(case DetailType
                                 when 201 then CostTotal
                                 else 0
                               end), 0) as Total201 ,
                    isnull(sum(case DetailType
                                 when 201 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal201 ,
                    isnull(sum(case DetailType
                                 when 202 then Qty
                                 else 0
                               end), 0) as Qty202 ,
                    isnull(sum(case DetailType
                                 when 202 then CostTotal
                                 else 0
                               end), 0) as Total202 ,
                    isnull(sum(case DetailType
                                 when 202 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal202 ,
                    isnull(sum(case DetailType
                                 when 203 then Qty
                                 else 0
                               end), 0) as Qty203 ,
                    isnull(sum(case DetailType
                                 when 203 then CostTotal
                                 else 0
                               end), 0) as Total203 ,
                    isnull(sum(case DetailType
                                 when 203 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal203 ,
                    isnull(sum(case DetailType
                                 when 204 then Qty
                                 else 0
                               end), 0) as Qty204 ,
                    isnull(sum(case DetailType
                                 when 204 then CostTotal
                                 else 0
                               end), 0) as Total204 ,
                    isnull(sum(case DetailType
                                 when 204 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal204 ,
                    isnull(sum(case DetailType
                                 when 205 then Qty
                                 else 0
                               end), 0) as Qty205 ,
                    isnull(sum(case DetailType
                                 when 205 then CostTotal
                                 else 0
                               end), 0) as Total205 ,
                    isnull(sum(case DetailType
                                 when 205 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal205 ,
                    isnull(sum(case DetailType
                                 when 206 then Qty
                                 else 0
                               end), 0) as Qty206 ,
                    isnull(sum(case DetailType
                                 when 206 then CostTotal
                                 else 0
                               end), 0) as Total206 ,
                    isnull(sum(case DetailType
                                 when 206 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal206 ,
                    isnull(sum(case DetailType
                                 when 207 then Qty
                                 else 0
                               end), 0) as Qty207 ,
                    isnull(sum(case DetailType
                                 when 207 then CostTotal
                                 else 0
                               end), 0) as Total207 ,
                    isnull(sum(case DetailType
                                 when 207 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal207 ,
                    isnull(sum(case DetailType
                                 when 208 then Qty
                                 else 0
                               end), 0) as Qty208 ,
                    isnull(sum(case DetailType
                                 when 208 then CostTotal
                                 else 0
                               end), 0) as Total208 ,
                    isnull(sum(case DetailType
                                 when 208 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal208 ,
                    isnull(sum(case DetailType
                                 when 209 then Qty
                                 else 0
                               end), 0) as Qty209 ,
                    isnull(sum(case DetailType
                                 when 209 then CostTotal
                                 else 0
                               end), 0) as Total209 ,
                    isnull(sum(case DetailType
                                 when 209 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal209 ,
                    isnull(sum(case DetailType
                                 when 210 then Qty
                                 else 0
                               end), 0) as Qty210 ,
                    isnull(sum(case DetailType
                                 when 210 then CostTotal
                                 else 0
                               end), 0) as Total210 ,
                    isnull(sum(case DetailType
                                 when 210 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal210 ,
                    isnull(sum(case DetailType
                                 when 212 then Qty
                                 else 0
                               end), 0) as Qty212 ,
                    isnull(sum(case DetailType
                                 when 212 then CostTotal
                                 else 0
                               end), 0) as Total212 ,
                    isnull(sum(case DetailType
                                 when 212 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal212 ,
                    isnull(sum(case DetailType
                                 when 213 then Qty
                                 else 0
                               end), 0) as Qty213 ,
                    isnull(sum(case DetailType
                                 when 213 then CostTotal
                                 else 0
                               end), 0) as Total213 ,
                    isnull(sum(case DetailType
                                 when 213 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal213 ,
                    isnull(sum(case DetailType
                                 when 214 then Qty
                                 else 0
                               end), 0) as Qty214 ,
                    isnull(sum(case DetailType
                                 when 214 then CostTotal
                                 else 0
                               end), 0) as Total214 ,
                    isnull(sum(case DetailType
                                 when 214 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal214 ,
                    isnull(sum(case DetailType
                                 when 215 then Qty
                                 else 0
                               end), 0) as Qty215 ,
                    isnull(sum(case DetailType
                                 when 215 then CostTotal
                                 else 0
                               end), 0) as Total215 ,
                    isnull(sum(case DetailType
                                 when 215 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal215 ,
                    isnull(sum(case DetailType
                                 when 216 then Qty
                                 else 0
                               end), 0) as Qty216 ,
                    isnull(sum(case DetailType
                                 when 216 then CostTotal
                                 else 0
                               end), 0) as Total216 ,
                    isnull(sum(case DetailType
                                 when 216 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal216 ,
                    isnull(sum(case DetailType
                                 when 218 then Qty
                                 else 0
                               end), 0) as Qty218 ,
                    isnull(sum(case DetailType
                                 when 218 then CostTotal
                                 else 0
                               end), 0) as Total218 ,
                    isnull(sum(case DetailType
                                 when 218 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal218 ,
                    isnull(sum(case DetailType
                                 when 220 then Qty
                                 else 0
                               end), 0) as Qty220 ,
                    isnull(sum(case DetailType
                                 when 220 then CostTotal
                                 else 0
                               end), 0) as Total220 ,
                    isnull(sum(case DetailType
                                 when 220 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal220 ,
                    isnull(sum(case DetailType
                                 when 221 then Qty
                                 else 0
                               end), 0) as Qty221 ,
                    isnull(sum(case DetailType
                                 when 221 then CostTotal
                                 else 0
                               end), 0) as Total221 ,
                    isnull(sum(case DetailType
                                 when 221 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal221 ,
                    isnull(sum(case DetailType
                                 when 301 then Qty
                                 else 0
                               end), 0) as Qty301 ,
                    isnull(sum(case DetailType
                                 when 301 then CostTotal
                                 else 0
                               end), 0) as Total301 ,
                    isnull(sum(case DetailType
                                 when 301 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal301 ,
                    isnull(sum(case DetailType
                                 when 401 then Qty
                                 else 0
                               end), 0) as Qty401 ,
                    isnull(sum(case DetailType
                                 when 401 then CostTotal
                                 else 0
                               end), 0) as Total401 ,
                    isnull(sum(case DetailType
                                 when 401 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal401
            from    #TempAllJXC3 a --where not (DetailType = 301 and (qty = 0 or CostTotal = 0)) 
		
            group by PtypeId ,
                    ColorId ,
                    SizeId	
	end                    
    if object_id('tempdb..#AllJXCKtypeIdTable') is not null 
        drop table #AllJXCKtypeIdTable
    if object_id('tempdb..#AllJXCPtypeIdTable') is not null 
        drop table #AllJXCPtypeIdTable        
    if object_id('tempdb..#TempAllJXC1') is not null 
        drop table #TempAllJXC1       
    if object_id('tempdb..#TempAllJXC2') is not null 
        drop table #TempAllJXC2       
    if object_id('tempdb..#TempAllJXC2q') is not null 
        drop table #TempAllJXC2q                      
    if object_id('tempdb..#TempAllJXC3') is not null 
        drop table #TempAllJXC3                               
        
end                            




GO




/******************************************20130722********************************************/

SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[PtypeBuySale]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[PtypeBuySale]
GO

SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO
/*      
商品进销存分析
效率提升40%
*/      
Create PROC PtypeBuySale
(      
  @dynTable as DynParameterTable readonly
  , @sqlCmd nvarchar(max) out --输出参数, 业务Sql片段
  , @decSql nvarchar(max) out --输出参数，参数声明Sql片段
  , @specSql nvarchar(max) out --输出参数，参数赋值Sql片段    
)       
AS 
BEGIN
	DECLARE @SQLCmd1 VARCHAR(MAX),@SQLCmd2 VARCHAR(8000) = ''
	--新增存储过程 GetDig，用来取小数配置。以后所有报表存储过程对小数位的取舍用以下方式。
	DECLARE  @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
	EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
	SET @SQLCmd1 = N''
	set @decSql = N'@dynParamTable as DynParameterTable readonly,@dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int'
	set @specSql = N'@dynParamTable,'+ CAST(@dig_qty AS NVARCHAR)+N','+ CAST(@dig_price AS NVARCHAR)+N','+CAST(@dig_total AS NVARCHAR)+N','+CAST(@dig_dis AS NVARCHAR)+N','+
	CAST(@dig_tax AS NVARCHAR)+N','+CAST(@dig_rate AS NVARCHAR)
	
	SELECT @decSql += nchar(10) + nchar(9) + N', @' + ParaField + N' ' + DataType,
	       @specSql += nchar(10) + nchar(9) + isnull(N', ''' + ParaValue + N'''', ', null')
    from @dynTable
    WHERE datatype <> ''
    
    DECLARE @branchmode VARCHAR(10),@jmph VARCHAR(50),@cgjh VARCHAR(50)
    SELECT @branchmode = paraValue FROM @dynTable WHERE paraField = 'branchmode'
    
    IF @branchmode = '0'   --内部机构
    BEGIN
    	SET @cgjh = '6,34'
    	SET @jmph = '222,224'
    END
    ELSE
    BEGIN
    	SET @cgjh = '232,234'
    	SET @jmph = '0'
    END
    
    DECLARE @Branchid VARCHAR(50),@Ktypeid VARCHAR(50),@SalePriceid VARCHAR(50),
    @Ptypecategory VARCHAR(10),@ShowFields VARCHAR(8000),@WhereCmd VARCHAR(8000)= '',@GroupBy VARCHAR(8000)='',@OrderBy VARCHAR(3000) = '',@Flag BIT = 0,
    @temp1fields VARCHAR(2000) = '',@temp1groupby VARCHAR(2000) = '',@ckshowfields VARCHAR(2000) = '',@datawhere VARCHAR(2000)='',
    @otherfields VARCHAR(2000) = '',@otherwhere VARCHAR(2000)= '',@billwhere VARCHAR(2000) = '',@transbillwhere VARCHAR(2000) = '',
    @transjoin VARCHAR(2000) = '',@colorid VARCHAR(20)= '',@sizeid VARCHAR(20)= '',@tbl1where VARCHAR(2000) = '',@transsql VARCHAR(2000) = '',
    @priceModeSQL VARCHAR(2000) = '',@billwhere_before VARCHAR(2000) = ''
    
    SELECT @Branchid = ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'branchid'
    SET @Branchid = SUBSTRING(@Branchid,1,LEN(@Branchid)-1)
    SELECT @Ktypeid = ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'ktypeid'
    SELECT @colorid = ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'colorid'
    SELECT @sizeid = ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'sizeid'
    SELECT @SalePriceid = ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'salepriceid'
    SELECT @Ptypecategory = ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'ptypecategory' 
    SELECT @ShowFields = ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'dlistfield'       
    SELECT @ShowFields = @ShowFields + ',' + ISNULL(paraValue,'') FROM @dynTable WHERE paraField = 'ddistdetailfield'    
    
    IF @Ptypecategory = ''
    SET @Ptypecategory = '1'
    
    IF @colorid <> ''
    BEGIN
		SET @tbl1where = @tbl1where + ' and gsd.colorid = @colorid '
		SET	@temp1groupby = @temp1groupby + 'gsd.colorid, '
    END
    
	
	IF @sizeid <> ''
	BEGIN
		SET @tbl1where = @tbl1where + ' and gsd.sizeid = @sizeid '
		SET	@temp1groupby = @temp1groupby + 'gsd.sizeid, '
	END
	

    IF @Ktypeid <> ''
    BEGIN
    	SET @Ktypeid = SUBSTRING(@Ktypeid,1,LEN(@Ktypeid)-1)
    END
    
    
    DECLARE @pc1 VARCHAR(2),@pc2 VARCHAR(2),@pc3 VARCHAR(2)
	SELECT @pc1 = a FROM Fn_splitWithOrderid(@ptypecategory,',') WHERE orderid = 1
	SELECT @pc2 = a FROM Fn_splitWithOrderid(@ptypecategory,',') WHERE orderid = 2
	SELECT @pc3 = a FROM Fn_splitWithOrderid(@ptypecategory,',') WHERE orderid = 3
    
    DECLARE @sumFields VARCHAR(8000) = '',@sumGroupBy VARCHAR(5000) = ''
    
    IF CHARINDEX('ptypeid',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + 'dly.ptypeid,'
	SET @GroupBy = @GroupBy + 'dly.ptypeid,'
	SET @OrderBy = @OrderBy + 'DATA.ptypeid,'
	SET @sumFields = @sumFields + 'c.ptypeid,'
	SET @sumGroupBy = @sumGroupBy + 'c.ptypeid,'
	END
    
    IF CHARINDEX('btypeid',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(select btypeid1 from ptype where typeid = dly.ptypeid) btypeid,'
	SET @OrderBy = @OrderBy + 'DATA.btypeid,'
	SET @sumFields = @sumFields + 'c.btypeid,'
	SET @sumGroupBy = @sumGroupBy + 'c.btypeid,'	
	SET @Flag = 1
	END
    
    IF CHARINDEX('branchid',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + 'dly.BranchId,'
	SET @GroupBy = @GroupBy + 'dly.BranchId,'
	SET @OrderBy = @OrderBy + 'DATA.BranchId,'
	SET @sumFields = @sumFields + 'c.BranchId,'
	SET @sumGroupBy = @sumGroupBy + 'c.BranchId,'	
	SET @temp1fields = @temp1fields + 'st.branchid,'
	SET @datawhere = @datawhere + ' and a.branchid = b.branchid '
	SET @otherfields = @otherfields + ' b.branchid, '
	SET @otherwhere = @otherwhere + ' b.branchid, '
	SET @billwhere = @billwhere + ' and a.branchid = d.branchid '
	SET @billwhere_before = @billwhere_before + ' and a.branchid = f.branchid '
	SET @transbillwhere = @transbillwhere + ' and a.branchid = e.branchid '
	END
    
    IF CHARINDEX('colorid',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + 'RIGHT(''''00000''''+ CAST(dly.ColorID AS VARCHAR),5) colorid,'
	SET @GroupBy = @GroupBy + 'dly.ColorID,'
	SET @OrderBy = @OrderBy + 'DATA.ColorID,'
	SET @sumFields = @sumFields + 'c.ColorID,'
	SET @temp1fields = @temp1fields + 'gsd.ColorID,'
	SET @sumGroupBy = @sumGroupBy + 'c.ColorID,'		
	SET @datawhere = @datawhere + ' and a.ColorID = b.ColorID'
	SET @otherfields = @otherfields + 'c.colorid,'
	SET @otherwhere = @otherwhere + ' c.colorid, '
    SET @billwhere = @billwhere + ' and a.colorid = d.colorid '
    SET @billwhere_before = @billwhere_before + ' and a.colorid = f.colorid '
    SET @transbillwhere = @transbillwhere + ' and a.colorid = e.colorid '			
	END
    
    IF CHARINDEX('sizeid',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + 'RIGHT(''''00000''''+ CAST(dly.SizeID AS VARCHAR),5) sizeid,'
	SET @GroupBy = @GroupBy + 'dly.SizeID,'
	SET @OrderBy = @OrderBy + 'DATA.SizeID,'
	SET @sumFields = @sumFields + 'c.SizeID,'
	SET @sumGroupBy = @sumGroupBy + 'c.SizeID,'
	SET @temp1fields = @temp1fields + 'gsd.SizeID,'
	SET @datawhere = @datawhere + ' and a.SizeID = b.SizeID'
	SET @otherfields = @otherfields + 'c.SizeID,'
	SET @otherwhere = @otherwhere + 'c.SizeID,'
	SET @billwhere = @billwhere + ' and a.SizeID = d.SizeID '
	SET @billwhere_before = @billwhere_before + ' and a.SizeID = f.SizeID '
    SET @transbillwhere = @transbillwhere + ' and a.SizeID = e.SizeID '					
	END
    
    IF CHARINDEX('assist1',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 1) assist1,'
	SET @OrderBy = @OrderBy + 'DATA.assist1,'
	SET @sumFields = @sumFields + 'c.assist1,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist1,'
	SET @Flag = 1	
	END
    
    IF CHARINDEX('assist2',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 2) assist2,'
	SET @OrderBy = @OrderBy + 'DATA.assist2,'
	SET @sumFields = @sumFields + 'c.assist2,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist2,'
	SET @Flag = 1			
	END
    
    IF CHARINDEX('assist3',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 3) assist3,'
	SET @OrderBy = @OrderBy + 'DATA.assist3,'
	SET @sumFields = @sumFields + 'c.assist3,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist3,'		
	SET @Flag = 1	
	END
    
    IF CHARINDEX('assist4',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 4) assist4,'
	SET @OrderBy = @OrderBy + 'DATA.assist4,'
	SET @sumFields = @sumFields + 'c.assist4,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist4,'		
	SET @Flag = 1	
	END
    
    IF CHARINDEX('assist5',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 5) assist5,'
	SET @OrderBy = @OrderBy + 'DATA.assist5,'
	SET @sumFields = @sumFields + 'c.assist5,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist5,'			
	SET @Flag = 1	
	END
    
    IF CHARINDEX('assist6',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 6) assist6,'
	SET @OrderBy = @OrderBy + 'DATA.assist6,'
	SET @sumFields = @sumFields + 'c.assist6,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist6,'			
	SET @Flag = 1	
	END
    
    IF CHARINDEX('assist7',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 7) assist7,'
	SET @OrderBy = @OrderBy + 'DATA.assist7,'
	SET @sumFields = @sumFields + 'c.assist7,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist7,'			
	SET @Flag = 1	
	END
	
    IF CHARINDEX('assist8',@ShowFields)>0 
    BEGIN
	SET @SQLCmd2 = @SQLCmd2 + '(SELECT UserName FROM dbo.AssistAttribute h WHERE EXISTS(SELECT 1 FROM dbo.PtypeAttribute g WHERE h.AttributeId = g.AttributeID AND g.PtypeId = dly.ptypeid)AND TypeID = 8) assist8,'
	SET @OrderBy = @OrderBy + 'DATA.assist8,'
	SET @sumFields = @sumFields + 'c.assist8,'
	SET @sumGroupBy = @sumGroupBy + 'c.assist8,'			
	SET @Flag = 1	
	END
	
	IF CHARINDEX('ptypecategory',@ShowFields)>0
	BEGIN
		IF @pc1 <> '0'
		BEGIN
			SET @SQLCmd2 = @SQLCmd2 + 'left(dly.ptypeid,'+ @pc1 +'*5) ptypeid1,'
	        SET @OrderBy = @OrderBy + 'DATA.ptypeid1,'
	        SET @sumFields = @sumFields + 'c.ptypeid1,'
	   	    SET @sumGroupBy = @sumGroupBy + 'c.ptypeid1,'     
	        SET @Flag = 1	
		END
	    
		IF @pc2 <> '0'
		BEGIN
			SET @SQLCmd2 = @SQLCmd2 + 'left(dly.ptypeid,'+ @pc2 +'*5) ptypeid2,'
	        SET @OrderBy = @OrderBy + 'DATA.ptypeid2,'
	        SET @sumFields = @sumFields + 'c.ptypeid2,'
	   	    SET @sumGroupBy = @sumGroupBy + 'c.ptypeid2,' 	        			
			SET @Flag = 1
		END
		
		IF @pc3 <> '0'
		BEGIN
			SET @SQLCmd2 = @SQLCmd2 + 'left(dly.ptypeid,'+ @pc3 +'*5) ptypeid3,'
	        SET @OrderBy = @OrderBy + 'DATA.ptypeid3,'
	        SET @sumFields = @sumFields + 'c.ptypeid3,'
	   	    SET @sumGroupBy = @sumGroupBy + 'c.ptypeid3,' 	        			
			SET @Flag = 1
		END
	END
	
    IF CHARINDEX('dly.ptypeid',@GroupBy)=0 
	BEGIN
		IF @Flag = 1
		BEGIN
			SET @GroupBy = @GroupBy + 'dly.ptypeid,'
		END
	END

	IF CHARINDEX('qty',@ShowFields)>0 
    BEGIN
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__cgjh__) THEN  SUM(dly.Qty) ELSE 0 END cgjhqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 1) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 1)) THEN SUM(dly.Qty) ELSE 0 END phjhqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 3) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 3)) THEN SUM(dly.Qty) ELSE 0 END dpjhqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 2) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 2)) THEN SUM(dly.Qty) ELSE 0 END thjhqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218,__cgjh__)) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode)) THEN SUM(dly.Qty) ELSE 0 END jhhjqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (12,100) THEN SUM(-dly.Qty) ELSE 0 END lsqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (11,24,45) THEN SUM(-dly.Qty) ELSE 0 END pfxsqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__jmph__) THEN SUM(-dly.Qty) ELSE 0 END jmphqty,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__jmph__,12,100,11,24,45) THEN SUM(-dly.Qty) ELSE 0 END xshjqty,'
			--SET @SQLCmd2 = @SQLCmd2 + 'SUM(f.Qty) kcqty,'
			SET @ckshowfields = @ckshowfields + 'ISNULL(b.kcqty,0)-ISNULL(d.qty,0) kcqty,'
			SET @ckshowfields = @ckshowfields + 'ISNULL(b.kcqty,0)-ISNULL(f.qty,0) kcsqqty,'
			SET @sumFields = @sumFields + 'sum(c.cgjhqty) cgjhqty,sum(c.phjhqty) phjhqty,sum(c.dpjhqty) dpjhqty,sum(c.thjhqty) thjhqty,sum(c.jhhjqty) jhhjqty,sum(c.lsqty) lsqty,sum(c.pfxsqty) pfxsqty,sum(c.jmphqty) jmphqty,sum(c.xshjqty) xshjqty,'
	END
	
	IF CHARINDEX('total',@ShowFields)>0 
    BEGIN
		IF @SalePriceid = '' --单据单价
		BEGIN
		    SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__cgjh__) THEN  ROUND( CONVERT(NUMERIC(24,10),SUM(dly.BargainTotal)),@dig_total) ELSE 0 END cgjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 1) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 1)) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.BargainTotal)),@dig_total) ELSE 0 END phjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 3) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 3)) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.BargainTotal)),@dig_total) ELSE 0 END dpjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 2) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 2)) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.BargainTotal)),@dig_total) ELSE 0 END thjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218,__cgjh__)) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode)) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.BargainTotal)),@dig_total) ELSE 0 END jhhjtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (12,100) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.BargainTotal)),@dig_total) ELSE 0 END lstotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (11,24,45) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.BargainTotal)),@dig_total) ELSE 0 END pfxstotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__jmph__) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.BargainTotal)),@dig_total) ELSE 0 END jmphtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__jmph__,12,100,11,24,45) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.BargainTotal)),@dig_total) ELSE 0 END xshjtotal,'
			SET @otherFields =  @otherFields +' sum(c.costtotal) total,'
			SET @priceModeSQL = @priceModeSQL + 'sum(isnull(gsd.total,0)) kctotal,'
		END
		ELSE    --其他参考价
		BEGIN
		    SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__cgjh__) THEN  ROUND( CONVERT(NUMERIC(24,10),SUM(dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END cgjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 1) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 1)) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END phjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 3) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 3))THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END dpjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218) AND dly.PHID = 2) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode AND dl.PHID = 2))THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END thjhtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN (dly.Vchtype IN (212,218,__cgjh__)) or (dly.VchType = 230 AND EXISTS(select 1 from dlyndx dl where dl.vchcode = dly.dlyvchcode)) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END jhhjtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (12,100) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END lstotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (11,24,45) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END pfxstotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__jmph__) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END jmphtotal,'
			SET @SQLCmd2 = @SQLCmd2 + 'CASE WHEN dly.Vchtype IN (__jmph__,12,100,11,24,45) THEN ROUND(CONVERT(NUMERIC(24,10),SUM(-dly.Qty))*ISNULL(dly.Price,0),@dig_total) ELSE 0 END xshjtotal,'
			SET @otherFields =  @otherFields +' ROUND(CONVERT(NUMERIC(24,10),sum(c.qty))*ISNULL(d.price,0),@dig_total) total,'
			SET @priceModeSQL = @priceModeSQL + 'CONVERT(NUMERIC(24,10),SUM(ISNULL(gsd.Qty,0)*ISNULL(' + CASE WHEN @SalePriceid = ''  then 'gs.price' else 'd.Price' END + ',0))) kctotal,'
		END
			--SET @SQLCmd2 = @SQLCmd2 + 'SUM(f.Qty*ISNULL(d.Price,0)) kctotal,'
			SET @ckshowfields = @ckshowfields + 'ISNULL(b.kctotal,0) - ISNULL(d.total,0) kctotal,'
			SET @ckshowfields = @ckshowfields + 'ISNULL(b.kctotal,0) - ISNULL(f.total,0) kcsqtotal,'
			SET @sumFields = @sumFields + 'sum(c.cgjhtotal) cgjhtotal,sum(c.phjhtotal) phjhtotal,sum(c.dpjhtotal) dpjhtotal,sum(c.thjhtotal) thjhtotal,sum(c.jhhjtotal) jhhjtotal,sum(c.lstotal) lstotal,sum(c.pfxstotal) pfxstotal,sum(c.jmphtotal) jmphtotal,sum(c.xshjtotal) xshjtotal,'
	END
	
	IF CHARINDEX('total',@ShowFields)>0 OR CHARINDEX('qty',@ShowFields)>0
		SET @GroupBy = @GroupBy + 'dly.phid,dly.dlyvchcode,'
		
	IF @SalePriceid <> ''
	--BEGIN
	--	SET @GroupBy = @GroupBy + 'b.costprice,'
	--	--SET @temp1fields = @temp1fields + 'gs.price,'
	--END
	--ELSE
	BEGIN
		SET @GroupBy = @GroupBy + 'dly.price,'
		SET @otherwhere = @otherwhere + 'd.price,'
		--SET @temp1fields = @temp1fields + 'd.price,'
	END		

	IF @Branchid = '00001' AND @Ktypeid = ''
	BEGIN
		SET @transjoin = @transjoin + ' LEFT JOIN #billtrans e ON e.ptypeid = a.ptypeid__transwhere__ '
		SET @transSql = @transSql + '
			--在途库
			IF object_id(''''tempdb..#billtrans'''') is not null   
			drop table #billtrans
			select tbl.* into #billtrans from (
				select __otherFileds__b.ptypeid,sum(c.qty) qty
				from dlyndx a inner join dlydata b on a.vchcode = b.vchcode
				inner join dlydatadetail c on b.dlyorder = c.dlyorder
				left join dbo.PtypePrice d ON d.Ptypeid = b.PtypeId AND d.PriceTypeid = @salepriceid
				where a.[date] > @billdate_e
				and a.draft = 4
				AND (@ptypeid IS NULL OR b.Ptypeid LIKE @ptypeid)
				'+CASE WHEN @Ktypeid IS NULL OR @Ktypeid='' THEN '' ELSE ' AND b.Ktypeid like @ktypeid' END +
				  CASE WHEN @colorid IS NULL OR @colorid='' THEN '' ELSE ' AND c.ColorID = @colorid' END +
				  CASE WHEN @sizeid IS NULL OR @sizeid='' THEN '' ELSE ' AND c.SizeID = @sizeid' END +'
				AND EXISTS(SELECT 1 FROM dbo.FN_GetStockListOfBranch(@oprid,'''''''','''''''') WHERE KtypeId = b.KtypeId)
				AND EXISTS(SELECT 1 FROM #tmpptype WHERE TypeID = b.PtypeId)
				and b.ktypeid = ''''99999''''
				and a.redold = ''''F''''
				and a.vchtype in (212,218,222,234) 
				group by __otherwhere__b.ptypeid
			) tbl'
	END

	SET @SQLCmd1 = '
		IF OBJECT_ID(''''tempdb..#tmpptype'''') is not null drop table #tmpptype
		create table #tmpptype (typeid varchar(50))
		
		IF EXISTS (SELECT name FROM sys.indexes
            WHERE name = N''''IX_PtypeBuySale_TypeID'''')
			DROP INDEX IX_PtypeBuySale_TypeID ON #tmpptype;
		CREATE CLUSTERED INDEX IX_PtypeBuySale_TypeID 
			ON #tmpptype(typeid); 
			
		insert into #tmpptype(typeid)
		select typeid from dbo.FN_GetPowerRangePList(@oprid,'''''''')


		IF OBJECT_ID(''''tempdb..#dlyptype'''') is not null drop table #dlyptype
		create table #dlyptype (ptypeid varchar(50),
								branchid varchar(50),
								colorid varchar(50),
								sizeid varchar(50),
								qty NUMERIC(24,10),
								BargainTotal NUMERIC(24,10),
								vchtype int,
								vchcode int,
								phid int,
								dlyvchcode int,
								ktypeid varchar(50),
								price NUMERIC(24,10))

		insert into #dlyptype(ptypeid,
							  branchid,
							  colorid,
							  sizeid,
							  qty,
							  BargainTotal,
							  vchtype,
							  vchcode,
							  phid,
							  dlyvchcode,
							  ktypeid,
							  price
							  )
		select b.ptypeid,b.branchid,c.colorid,c.sizeid,
		case when a.vchtype in (212,218) and a.draft = 2 and a.branchid = b.branchid then c.qty
		     when a.vchtype not in (212,218) then c.qty
			 else 0 end qty,
		case when a.vchtype in (212,218) and a.draft = 2 and a.branchid = b.branchid then c.BargainTotal 
		     when a.vchtype not in (212,218) then c.BargainTotal
		     else 0 end BargainTotal,
		a.vchtype,a.vchcode,a.phid,a.dlyvchcode,b.ktypeid,ISNULL(d.price,0)
		FROM DlyNdx a INNER JOIN dbo.DlyData b ON a.vchcode = b.vchcode
		INNER JOIN dbo.DlyDataDetail c ON b.DlyOrder = c.DlyOrder
		LEFT JOIN dbo.PtypePrice d ON d.Ptypeid = b.PtypeId AND d.PriceTypeid = @salepriceid
		WHERE a.[Date] BETWEEN @billdate_s AND @billdate_e
		AND a.Vchtype IN (6,11,12,24,34,45,100,212,218,222,224,232,234,230)
		AND a.Draft IN (2,4)
		AND a.Redold = ''''F''''
	    AND (@branchid IS NULL OR b.Branchid LIKE @branchid)
	    '+CASE WHEN @Ktypeid IS NULL OR @Ktypeid='' THEN '' ELSE ' AND b.Ktypeid like @ktypeid' END +
		  CASE WHEN @colorid IS NULL OR @colorid='' THEN '' ELSE ' AND c.ColorID = @colorid' END +
		  CASE WHEN @sizeid IS NULL OR @sizeid='' THEN '' ELSE ' AND c.SizeID = @sizeid' END +'
		AND (@ptypeid IS NULL OR b.Ptypeid LIKE @ptypeid)
		AND b.KtypeId <> ''''99999''''
		
		--删除数量为0的数据
		delete from #dlyptype where qty = 0
		
	    --单据数量金额 结束日期之后数据
		IF object_id(''''tempdb..#billtbl'''') is not null   
		drop table #billtbl
		select tbl.* into #billtbl from (
			select __otherFileds__b.ptypeid,sum(c.qty) qty
			from dlyndx a inner join dlydata b on a.vchcode = b.vchcode
			inner join dlydatadetail c on b.dlyorder = c.dlyorder
			left join dbo.PtypePrice d ON d.Ptypeid = b.PtypeId AND d.PriceTypeid = @salepriceid
			where a.[date] > @billdate_e
			and a.draft in (2,4)
			AND (@branchid IS NULL OR b.Branchid LIKE @branchid) '
			+ CASE WHEN @Ktypeid IS NULL OR @Ktypeid='' THEN '' ELSE ' AND b.Ktypeid like @ktypeid' END +
			  CASE WHEN @colorid IS NULL OR @colorid='' THEN '' ELSE ' AND c.ColorID = @colorid' END +
			  CASE WHEN @sizeid IS NULL OR @sizeid='' THEN '' ELSE ' AND c.SizeID = @sizeid' END +'
			AND (@ptypeid IS NULL OR b.Ptypeid LIKE @ptypeid)
			AND EXISTS(SELECT 1 FROM dbo.FN_GetStockListOfBranch(@oprid,'''''''','''''''') WHERE KtypeId = b.KtypeId)
		    AND EXISTS(SELECT 1 FROM #tmpptype WHERE TypeID = b.PtypeId)
			and b.ktypeid <> ''''99999''''
			and a.redold = ''''F''''
			and a.vchtype in (6,9,11,12,14,16,17,21,24,34,45,57,100,126,139,150,212,218,222,224,230,234,251,252) 
			group by __otherwhere__b.ptypeid
		) tbl

	    --单据数量金额 开始日期之后数据
		IF object_id(''''tempdb..#billtbl_before'''') is not null   
		drop table #billtbl_before
		select tbl.* into #billtbl_before from (
			select __otherFileds__b.ptypeid,sum(c.qty) qty
			from dlyndx a inner join dlydata b on a.vchcode = b.vchcode
			inner join dlydatadetail c on b.dlyorder = c.dlyorder
			left join dbo.PtypePrice d ON d.Ptypeid = b.PtypeId AND d.PriceTypeid = @salepriceid
			where a.[date] >= @billdate_s
			and a.draft in (2,4)
			AND (@branchid IS NULL OR b.Branchid LIKE @branchid) '
			+ CASE WHEN @Ktypeid IS NULL OR @Ktypeid='' THEN '' ELSE ' AND b.Ktypeid like @ktypeid' END +
			  CASE WHEN @colorid IS NULL OR @colorid='' THEN '' ELSE ' AND c.ColorID = @colorid' END +
			  CASE WHEN @sizeid IS NULL OR @sizeid='' THEN '' ELSE ' AND c.SizeID = @sizeid' END +'
			AND (@ptypeid IS NULL OR b.Ptypeid LIKE @ptypeid)
			AND EXISTS(SELECT 1 FROM dbo.FN_GetStockListOfBranch(@oprid,'''''''','''''''') WHERE KtypeId = b.KtypeId)
		    AND EXISTS(SELECT 1 FROM #tmpptype WHERE TypeID = b.PtypeId)
			and b.ktypeid <> ''''99999''''
			and a.redold = ''''F''''
			and a.vchtype in (6,9,11,12,14,16,17,21,24,34,45,57,100,126,139,150,212,218,222,224,230,234,251,252) 
			group by __otherwhere__b.ptypeid
		) tbl

		__transql__

		IF object_id(''''tempdb..#tbl'''') is not null   
		drop table #tbl
		select tbl.* into #tbl from(
		SELECT __Fields__              
		FROM #dlyptype dly
		where (@btypeid is NULL OR EXISTS (SELECT 1 FROM dbo.Ptype p WHERE p.typeid = dly.ptypeid AND p.btypeid1 like @btypeid ))
		AND EXISTS (SELECT 1 FROM dbo.Ptype p WHERE p.TypeId =dly.Ptypeid AND p.[stop] IN (CASE p.stop when 1 then @containsstop else 0 end)) 
		AND (@assist1 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist1))
		AND (@assist2 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist2))
		AND (@assist3 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist3))
		AND (@assist4 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist4))
		AND (@assist5 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist5))
		AND (@assist6 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist6))
		AND (@assist7 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist7))
		AND (@assist8 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = dly.PtypeId AND pa.AttributeID = @assist8))
		AND EXISTS(SELECT 1 FROM dbo.FN_GetStockListOfBranch(@oprid,'''''''','''''''') WHERE KtypeId = dly.KtypeId)
		AND EXISTS(SELECT 1 FROM #tmpptype WHERE TypeID = dly.PtypeId)
		GROUP BY __groupby__dly.vchtype,dly.vchcode
	) tbl
	
	IF object_id(''''tempdb..#tbl1'''') is not null   
	drop table #tbl1
	select tbl1.* into #tbl1 from(
	SELECT __temp1fields__gs.PtypeId,__kctotal__sum(ISNULL(gsd.Qty,0)) kcqty
	FROM dbo.GoodsStocks gs INNER JOIN dbo.Goodsstockdetail gsd ON gs.OrderId = gsd.OrderId
	inner join dbo.Stock st on gs.ktypeid = st.typeid
	LEFT JOIN dbo.PtypePrice d ON d.Ptypeid = gs.PtypeId AND d.PriceTypeid = @salepriceid
	WHERE EXISTS(SELECT 1 FROM dbo.FN_GetStockListOfBranch(@oprid,'''''+ @Branchid +''''',''''' + @Ktypeid + ''''') fn WHERE fn.KtypeId = gs.ktypeid)
	AND EXISTS(SELECT 1 FROM #tmpptype WHERE TypeID = gs.PtypeId)
	__tbl1where__
	group by __temp1groupby__gs.ptypeid
	) tbl1;
	
	with Data AS (
		select __datafields__a.*
		from (select __sumField__
				from #tbl c
				group by __sumgroup__) a LEFT JOIN #tbl1 b ON a.ptypeid = b.ptypeid __datawhere__
				LEFT JOIN #billtbl d ON a.ptypeid = d.ptypeid__billwhere__
				LEFT JOIN #billtbl_before f ON a.ptypeid = f.ptypeid__billwherebefore__
				__trans__
		),'
   
   	-- 排序信息
	declare @sortInfo varchar(255) = isnull((select ParaValue from @dynTable where ParaField = '__SortInfo__') + ',', '')
	-- 排序联接信息
	declare @sortJoinInfo varchar(555) = isnull((select replace(ParaValue, '__LeftTable__', 'Data') from @dynTable where ParaField = '__SortJoinInfo__'), '')
   
   set @sqlCmd = cast(
	(
		@SQLCmd1
		+ '
		__ReportData__ AS (
		select dense_rank() over (order by ' + @sortInfo + '__orderby__ DESC) __RowNo__,DATA.*
		from Data ' + @sortJoinInfo + ')'
	) as nvarchar(max))
   
   SET @SQLCmd2 = SUBSTRING(@SQLCmd2,1,LEN(@SQLCmd2)-1)
   set @sqlCmd = replace(@sqlCmd,'__Fields__',@SQLCmd2)
   --SET @GroupBy = SUBSTRING(@GroupBy,1,LEN(@GroupBy)-1)
   set @sqlCmd = replace(@sqlCmd,'__groupby__',@GroupBy)
   SET @OrderBy = SUBSTRING(@OrderBy,1,LEN(@OrderBy)-1)
   SET @sumFields = SUBSTRING(@sumFields,1,LEN(@sumFields)-1)
   SET @sumGroupBy = SUBSTRING(@sumGroupBy,1,LEN(@sumGroupBy)-1)
   set @sqlCmd = replace(@sqlCmd,'__orderby__',@OrderBy)
   set @sqlCmd = replace(@sqlCmd,'__sumField__',@sumFields)
   set @sqlCmd = replace(@sqlCmd,'__sumgroup__',@sumGroupBy)      
   set @sqlCmd = replace(@sqlCmd,'__temp1fields__',@temp1fields)
   set @sqlCmd = replace(@sqlCmd,'__temp1groupby__',@temp1fields)
   set @sqlCmd = replace(@sqlCmd,'__datafields__',@ckshowfields)
   set @sqlCmd = replace(@sqlCmd,'__datawhere__',@datawhere) 
   set @sqlCmd = replace(@sqlCmd,'__transql__',@transSql)
   set @sqlCmd = replace(@sqlCmd,'__trans__',@transjoin)
   set @sqlCmd = replace(@sqlCmd,'__otherFileds__',@otherFields) 
   set @sqlCmd = replace(@sqlCmd,'__otherwhere__',@otherwhere)
   set @sqlCmd = replace(@sqlCmd,'__billwhere__',@billwhere)
   set @sqlCmd = replace(@sqlCmd,'__billwherebefore__',@billwhere_before)
   set @sqlCmd = replace(@sqlCmd,'__transwhere__',@transbillwhere)
   set @sqlCmd = replace(@sqlCmd,'__cgjh__',@cgjh)
   set @sqlCmd = replace(@sqlCmd,'__jmph__',@jmph)
   set @sqlCmd = replace(@sqlCmd,'__tbl1where__',@tbl1where)
   set @sqlCmd = replace(@sqlCmd,'__kctotal__',@priceModeSQL)
   
   
END
GO

/****** Object:  StoredProcedure [dbo].[FzGetAllPowerPro]    Script Date: 03/13/2012 16:01:35 ******/
IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[FZGetAllJXC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].FZGetAllJXC
GO


/****** Object:  StoredProcedure [dbo].[FZGetAllJXC]    Script Date: 03/13/2012 16:01:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].FZGetAllJXC
(
      @BranchId varchar(8000) ,
      @PtypeId varchar(50) ,
      @KtypeId varchar(8000) ,
      @DateBegin varchar(15) ,
      @DateEnd varchar(15) ,
      @Displaymode int ,
      @OperatorId VARCHAR(50),
      @OnlyCheckChange bit = 0
)
as
begin

	Declare @NdxMaxId int
	Declare @QryMaxId int
	select @NdxMaxId = MAX(vchcode) from dlyndx
	select @QryMaxId = cast(subvalue as int) from QueryVchcodeRec where subname = 'AllPowerMaxVch'
	--新增存储过程 GetDig，用来取小数配置。以后所有报表存储过程对小数位的取舍用以下方式。
    DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
    EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
	
	if (@NdxMaxId > @QryMaxId) or exists(select 1 from TBAllPowerChangeVchcode where vchcode <= @QryMaxId)
	begin
	        if object_id('tempdb..#InoutVchTypeTemp') is not null 
	        	drop table #InoutVchTypeTemp
		Delete from TBAllPowerChangeVchcode where vchcode > @QryMaxId		
		Create Table #InoutVchTypeTemp
		(
		 VchType int,
		 DetailType int,
		 Phid int
		)
			insert into #InoutVchTypeTemp select vchtype,detailtype,phid from 
			(Select 34 as vchtype,101 as detailtype,0 as phid union all
			Select 45 as vchtype,102 as detailtype,0 as phid union all
			Select 101 as vchtype,102 as detailtype,0 as phid union all
			Select 16 as vchtype,103 as detailtype,0 as phid union all
			Select 14 as vchtype,104 as detailtype,0 as phid union all		
			Select 126 as vchtype,105 as detailtype,0 as phid union all
			Select 17 as vchtype,106 as detailtype,0 as phid union all
			Select 21 as vchtype,107 as detailtype,0 as phid union all
			Select 24 as vchtype,108 as detailtype,0 as phid union all
			Select 57 as vchtype,109 as detailtype,0 as phid union all
			Select 13 as vchtype,112 as detailtype,0 as phid union all
			Select 101 as vchtype,112 as detailtype,0 as phid union all
			Select 100 as vchtype,112 as detailtype,0 as phid union all
			Select 12 as vchtype,112 as detailtype,0 as phid union all
			Select 212 as vchtype,113 as detailtype,1 as phid union all
			Select 218 as vchtype,113 as detailtype,1 as phid union all
			Select 212 as vchtype,113 as detailtype,3 as phid union all
			Select 218 as vchtype,113 as detailtype,3 as phid union all
			Select 224 as vchtype,115 as detailtype,0 as phid union all
			Select 230 as vchtype,116 as detailtype,0 as phid union all
			Select 212 as vchtype,118 as detailtype,2 as phid union all
			Select 218 as vchtype,118 as detailtype,2 as phid union all
			Select 150 as vchtype,120 as detailtype,0 as phid union all
			Select 252 as vchtype,121 as detailtype,0 as phid union all
			Select 11 as vchtype,201 as detailtype,0 as phid union all
			Select 6 as vchtype,202 as detailtype,0 as phid union all
			Select 16 as vchtype,203 as detailtype,0 as phid union all
			Select 139 as vchtype,204 as detailtype,0 as phid union all
			Select 17 as vchtype,205 as detailtype,0 as phid union all
			Select 9 as vchtype,206 as detailtype,0 as phid union all
			Select 21 as vchtype,207 as detailtype,0 as phid union all
			Select 24 as vchtype,208 as detailtype,0 as phid union all
			Select 57 as vchtype,209 as detailtype,0 as phid union all
			Select 13 as vchtype,212 as detailtype,0 as phid union all
			Select 101 as vchtype,212 as detailtype,0 as phid union all
			Select 100 as vchtype,212 as detailtype,0 as phid union all
			Select 12 as vchtype,212 as detailtype,0 as phid union all
			Select 212 as vchtype,213 as detailtype,1 as phid union all
			Select 212 as vchtype,213 as detailtype,3 as phid union all
			Select 218 as vchtype,213 as detailtype,1 as phid union all
			Select 218 as vchtype,213 as detailtype,3 as phid union all
			Select 222 as vchtype,215 as detailtype,0 as phid union all
			Select 224 as vchtype,215 as detailtype,0 as phid union all
			Select 230 as vchtype,216 as detailtype,0 as phid union all
			Select 212 as vchtype,218 as detailtype,2 as phid union all
			Select 218 as vchtype,218 as detailtype,2 as phid union all
			Select 150 as vchtype,220 as detailtype,0 as phid union all
			Select 251 as vchtype,221 as detailtype,0 as phid
			) a	

		Insert into TableForAllJXC select a.phid,b.PtypeId,c.ColorID,c.SizeID,b.BranchId,b.ktypeId,CONVERT(NUMERIC(24,10),sum(c.Qty)),CONVERT(NUMERIC(24,10),sum(c.CostTotal)),a.date,x.DetailType
			 From DlyNdx a inner join DlyData b on a.Vchcode = b.Vchcode inner join dlydatadetail c on b.DlyOrder = c.DlyOrder --inner join #AllJXCKtypeIdTable f on b.KtypeId = f.KtypeId
			  Inner join #InoutVchTypeTemp x on a.Vchtype = x.VchType and x.Phid = a.PhId 
				--由于红冲单据的存在 所以出入库不能用正负号判断，故去掉
			 AND  
			 (
				(
					(
						(( c.qty > 0) and x.DetailType < 200) 
						OR  
						(( c.qty < 0) and x.DetailType > 200)
					) 
					AND a.RedWord = 'F'
				)
				OR
				(
					(
						(( c.qty > 0) and x.DetailType > 200) 
						OR  
						(( c.qty < 0) and x.DetailType < 200)
					) 
					AND a.RedWord = 'T'
				)
			)
			and ((b.Vchcode > @QryMaxId) or (b.vchcode in (select vchcode from TBAllPowerChangeVchcode) and ((b.ktypeid = '99999' and b.Qty < 0) or b.usedtype = 2)))
			----将新增单据数据以及验收的老单据数据写入表中
		group by a.phid,b.PtypeId,c.ColorID,c.SizeID ,b.BranchId,b.ktypeId ,a.date,x.DetailType
		Order by a.date				
		drop table #InoutVchTypeTemp
		Update QueryVchcodeRec set subvalue = cast(@NdxMaxId as varchar) where subname = 'AllPowerMaxVch'		
		Delete from TBAllPowerChangeVchcode where vchcode <= @QryMaxId		
	end
		
    if object_id('tempdb..#AllJXCKtypeIdTable') is not null 
        drop table #AllJXCKtypeIdTable
    if object_id('tempdb..#AllJXCPtypeIdTable') is not null 
        drop table #AllJXCPtypeIdTable        
        
    select  KtypeId
    Into    #AllJXCKtypeIdTable
    from    FN_GetStockListOfBranch(@OperatorID, @BranchId, @Ktypeid) a
    where   exists ( select 1
                     from   Stock b
                     where  a.ktypeid = b.typeid
                            and b.branchtype <> 4 )
	create CLUSTERED index TempIdx1 on #AllJXCKtypeIdTable(Ktypeid)                             

	Select typeId,retailPrice
	Into #AllJXCPtypeIdTable
	from FN_GetPowerRangePList(@OperatorId, @PtypeId) a
        where @OnlyCheckChange = 0 or (@OnlyCheckChange = 1 and exists (Select 1 from TableForAllJXC x where Datadate between @DateBegin and @DateEnd and a.typeId = x.PtypeId)) 
	
	create CLUSTERED index TempIdx2 on #AllJXCPtypeIdTable(typeId)                    
	
    if @DisplayMode = 0 
        begin
			select Ptypeid,case when (detailtype > 200 and detailtype < 300) then -SUM(Qty) else SUM(Qty) end as qty,
				case when (detailtype > 200 and detailtype < 300) then -SUM(CostTotal) else SUM(CostTotal) end as costtotal,	detailtype,
						CASE WHEN (detailtype > 200 and detailtype < 300) THEN -sum(RetailTotal) ELSE sum(RetailTotal) END as RetailTotal into #TempAllJXC1 from 
				(select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	detailtype,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as RetailTotal from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate between @DateBegin and @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,Left(PtypeId, Len(@PtypeId) + 5)
				union all
				select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,-SUM(Qty) as qty,-SUM(CostTotal) as costtotal,	401,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),-Qty)*CONVERT(NUMERIC(24,10),c.RetailPrice))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate > @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,Left(PtypeId, Len(@PtypeId) + 5) 
				union all
				select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	301,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate < @DateBegin
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by Left(PtypeId, Len(@PtypeId) + 5)
				union all (select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(qty) as qty,SUM(total) as costtotal,301 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from IniGoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by Left(PtypeId, Len(@PtypeId) + 5))
				union all (select Left(PtypeId, Len(@PtypeId) + 5) as PtypeId,SUM(qty) as qty,SUM(total) as costtotal,401 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from GoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by Left(PtypeId, Len(@PtypeId) + 5))						
				) a
				group by PtypeId,DetailType



				
            select  PtypeId ,
                                      isnull(sum(case DetailType
                                 when 101 then Qty
                                 else 0
                               end), 0) as Qty101 ,
                    isnull(sum(case DetailType
                                 when 101 then CostTotal
                                 else 0
                               end), 0) as Total101 ,
                    isnull(sum(case DetailType
                                 when 101 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal101 ,
                    isnull(sum(case DetailType
                                 when 102 then Qty
                                 else 0
                               end), 0) as Qty102 ,
                    isnull(sum(case DetailType
                                 when 102 then CostTotal
                                 else 0
                               end), 0) as Total102 ,
                    isnull(sum(case DetailType
                                 when 102 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal102 ,
                    isnull(sum(case DetailType
                                 when 103 then Qty
                                 else 0
                               end), 0) as Qty103 ,
                    isnull(sum(case DetailType
                                 when 103 then CostTotal
                                 else 0
                               end), 0) as Total103 ,
                    isnull(sum(case DetailType
                                 when 103 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal103 ,
                    isnull(sum(case DetailType
                                 when 104 then Qty
                                 else 0
                               end), 0) as Qty104 ,
                    isnull(sum(case DetailType
                                 when 104 then CostTotal
                                 else 0
                               end), 0) as Total104 ,
                    isnull(sum(case DetailType
                                 when 104 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal104 ,
                    isnull(sum(case DetailType
                                 when 105 then Qty
                                 else 0
                               end), 0) as Qty105 ,
                    isnull(sum(case DetailType
                                 when 105 then CostTotal
                                 else 0
                               end), 0) as Total105 ,
                    isnull(sum(case DetailType
                                 when 105 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal105 ,
                    isnull(sum(case DetailType
                                 when 106 then Qty
                                 else 0
                               end), 0) as Qty106 ,
                    isnull(sum(case DetailType
                                 when 106 then CostTotal
                                 else 0
                               end), 0) as Total106 ,
                    isnull(sum(case DetailType
                                 when 106 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal106 ,
                    isnull(sum(case DetailType
                                 when 107 then Qty
                                 else 0
                               end), 0) as Qty107 ,
                    isnull(sum(case DetailType
                                 when 107 then CostTotal
                                 else 0
                               end), 0) as Total107 ,
                    isnull(sum(case DetailType
                                 when 107 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal107 ,
                    isnull(sum(case DetailType
                                 when 108 then Qty
                                 else 0
                               end), 0) as Qty108 ,
                    isnull(sum(case DetailType
                                 when 108 then CostTotal
                                 else 0
                               end), 0) as Total108 ,
                    isnull(sum(case DetailType
                                 when 108 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal108 ,
                    isnull(sum(case DetailType
                                 when 109 then Qty
                                 else 0
                               end), 0) as Qty109 ,
                    isnull(sum(case DetailType
                                 when 109 then CostTotal
                                 else 0
                               end), 0) as Total109 ,
                    isnull(sum(case DetailType
                                 when 109 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal109 ,
                    isnull(sum(case DetailType
                                 when 110 then Qty
                                 else 0
                               end), 0) as Qty110 ,
                    isnull(sum(case DetailType
                                 when 110 then CostTotal
                                 else 0
                               end), 0) as Total110 ,
                    isnull(sum(case DetailType
                                 when 110 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal110 ,
                    isnull(sum(case DetailType
                                 when 112 then Qty
                                 else 0
                               end), 0) as Qty112 ,
                    isnull(sum(case DetailType
                                 when 112 then CostTotal
                                 else 0
                               end), 0) as Total112 ,
                    isnull(sum(case DetailType
                                 when 112 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal112 ,
                    isnull(sum(case DetailType
                                 when 113 then Qty
                                 else 0
                               end), 0) as Qty113 ,
                    isnull(sum(case DetailType
                                 when 113 then CostTotal
                                 else 0
                               end), 0) as Total113 ,
                    isnull(sum(case DetailType
                                 when 113 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal113 ,
                    isnull(sum(case DetailType
                                 when 114 then Qty
                                 else 0
                               end), 0) as Qty114 ,
                    isnull(sum(case DetailType
                                 when 114 then CostTotal
                                 else 0
                               end), 0) as Total114 ,
                    isnull(sum(case DetailType
                                 when 114 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal114 ,
                    isnull(sum(case DetailType
                                 when 115 then Qty
                                 else 0
                               end), 0) as Qty115 ,
                    isnull(sum(case DetailType
                                 when 115 then CostTotal
                                 else 0
                               end), 0) as Total115 ,
                    isnull(sum(case DetailType
                                 when 115 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal115 ,
                    isnull(sum(case DetailType
                                 when 116 then Qty
                                 else 0
                               end), 0) as Qty116 ,
                    isnull(sum(case DetailType
                                 when 116 then CostTotal
                                 else 0
                               end), 0) as Total116 ,
                    isnull(sum(case DetailType
                                 when 116 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal116 ,
                    isnull(sum(case DetailType
                                 when 118 then Qty
                                 else 0
                               end), 0) as Qty118 ,
                    isnull(sum(case DetailType
                                 when 118 then CostTotal
                                 else 0
                               end), 0) as Total118 ,
                    isnull(sum(case DetailType
                                 when 118 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal118 ,
                    isnull(sum(case DetailType
                                 when 120 then Qty
                                 else 0
                               end), 0) as Qty120 ,
                    isnull(sum(case DetailType
                                 when 120 then CostTotal
                                 else 0
                               end), 0) as Total120 ,
                    isnull(sum(case DetailType
                                 when 120 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal120 ,
                    isnull(sum(case DetailType
                                 when 121 then Qty
                                 else 0
                               end), 0) as Qty121 ,
                    isnull(sum(case DetailType
                                 when 121 then CostTotal
                                 else 0
                               end), 0) as Total121 ,
                    isnull(sum(case DetailType
                                 when 121 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal121 ,
                    isnull(sum(case DetailType
                                 when 201 then Qty
                                 else 0
                               end), 0) as Qty201 ,
                    isnull(sum(case DetailType
                                 when 201 then CostTotal
                                 else 0
                               end), 0) as Total201 ,
                    isnull(sum(case DetailType
                                 when 201 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal201 ,
                    isnull(sum(case DetailType
                                 when 202 then Qty
                                 else 0
                               end), 0) as Qty202 ,
                    isnull(sum(case DetailType
                                 when 202 then CostTotal
                                 else 0
                               end), 0) as Total202 ,
                    isnull(sum(case DetailType
                                 when 202 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal202 ,
                    isnull(sum(case DetailType
                                 when 203 then Qty
                                 else 0
                               end), 0) as Qty203 ,
                    isnull(sum(case DetailType
                                 when 203 then CostTotal
                                 else 0
                               end), 0) as Total203 ,
                    isnull(sum(case DetailType
                                 when 203 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal203 ,
                    isnull(sum(case DetailType
                                 when 204 then Qty
                                 else 0
                               end), 0) as Qty204 ,
                    isnull(sum(case DetailType
                                 when 204 then CostTotal
                                 else 0
                               end), 0) as Total204 ,
                    isnull(sum(case DetailType
                                 when 204 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal204 ,
                    isnull(sum(case DetailType
                                 when 205 then Qty
                                 else 0
                               end), 0) as Qty205 ,
                    isnull(sum(case DetailType
                                 when 205 then CostTotal
                                 else 0
                               end), 0) as Total205 ,
                    isnull(sum(case DetailType
                                 when 205 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal205 ,
                    isnull(sum(case DetailType
                                 when 206 then Qty
                                 else 0
                               end), 0) as Qty206 ,
                    isnull(sum(case DetailType
                                 when 206 then CostTotal
                                 else 0
                               end), 0) as Total206 ,
                    isnull(sum(case DetailType
                                 when 206 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal206 ,
                    isnull(sum(case DetailType
                                 when 207 then Qty
                                 else 0
                               end), 0) as Qty207 ,
                    isnull(sum(case DetailType
                                 when 207 then CostTotal
                                 else 0
                               end), 0) as Total207 ,
                    isnull(sum(case DetailType
                                 when 207 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal207 ,
                    isnull(sum(case DetailType
                                 when 208 then Qty
                                 else 0
                               end), 0) as Qty208 ,
                    isnull(sum(case DetailType
                                 when 208 then CostTotal
                                 else 0
                               end), 0) as Total208 ,
                    isnull(sum(case DetailType
                                 when 208 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal208 ,
                    isnull(sum(case DetailType
                                 when 209 then Qty
                                 else 0
                               end), 0) as Qty209 ,
                    isnull(sum(case DetailType
                                 when 209 then CostTotal
                                 else 0
                               end), 0) as Total209 ,
                    isnull(sum(case DetailType
                                 when 209 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal209 ,
                    isnull(sum(case DetailType
                                 when 210 then Qty
                                 else 0
                               end), 0) as Qty210 ,
                    isnull(sum(case DetailType
                                 when 210 then CostTotal
                                 else 0
                               end), 0) as Total210 ,
                    isnull(sum(case DetailType
                                 when 210 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal210 ,
                    isnull(sum(case DetailType
                                 when 212 then Qty
                                 else 0
                               end), 0) as Qty212 ,
                    isnull(sum(case DetailType
                                 when 212 then CostTotal
                                 else 0
                               end), 0) as Total212 ,
                    isnull(sum(case DetailType
                                 when 212 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal212 ,
                    isnull(sum(case DetailType
                                 when 213 then Qty
                                 else 0
                               end), 0) as Qty213 ,
                    isnull(sum(case DetailType
                                 when 213 then CostTotal
                                 else 0
                               end), 0) as Total213 ,
                    isnull(sum(case DetailType
                                 when 213 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal213 ,
                    isnull(sum(case DetailType
                                 when 214 then Qty
                                 else 0
                               end), 0) as Qty214 ,
                    isnull(sum(case DetailType
                                 when 214 then CostTotal
                                 else 0
                               end), 0) as Total214 ,
                    isnull(sum(case DetailType
                                 when 214 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal214 ,
                    isnull(sum(case DetailType
                                 when 215 then Qty
                                 else 0
                               end), 0) as Qty215 ,
                    isnull(sum(case DetailType
                                 when 215 then CostTotal
                                 else 0
                               end), 0) as Total215 ,
                    isnull(sum(case DetailType
                                 when 215 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal215 ,
                    isnull(sum(case DetailType
                                 when 216 then Qty
                                 else 0
                               end), 0) as Qty216 ,
                    isnull(sum(case DetailType
                                 when 216 then CostTotal
                                 else 0
                               end), 0) as Total216 ,
                    isnull(sum(case DetailType
                                 when 216 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal216 ,
                    isnull(sum(case DetailType
                                 when 218 then Qty
                                 else 0
                               end), 0) as Qty218 ,
                    isnull(sum(case DetailType
                                 when 218 then CostTotal
                                 else 0
                               end), 0) as Total218 ,
                    isnull(sum(case DetailType
                                 when 218 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal218 ,
                    isnull(sum(case DetailType
                                 when 220 then Qty
                                 else 0
                               end), 0) as Qty220 ,
                    isnull(sum(case DetailType
                                 when 220 then CostTotal
                                 else 0
                               end), 0) as Total220 ,
                    isnull(sum(case DetailType
                                 when 220 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal220 ,
                    isnull(sum(case DetailType
                                 when 221 then Qty
                                 else 0
                               end), 0) as Qty221 ,
                    isnull(sum(case DetailType
                                 when 221 then CostTotal
                                 else 0
                               end), 0) as Total221 ,
                    isnull(sum(case DetailType
                                 when 221 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal221 ,
                    isnull(sum(case DetailType
                                 when 301 then Qty
                                 else 0
                               end), 0) as Qty301 ,
                    isnull(sum(case DetailType
                                 when 301 then CostTotal
                                 else 0
                               end), 0) as Total301 ,
                    isnull(sum(case DetailType
                                 when 301 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal301 ,
                    isnull(sum(case DetailType
                                 when 401 then Qty
                                 else 0
                               end), 0) as Qty401 ,
                    isnull(sum(case DetailType
                                 when 401 then CostTotal
                                 else 0
                               end), 0) as Total401 ,
                    isnull(sum(case DetailType
                                 when 401 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal401
            from    #TempAllJXC1 a --where not (DetailType = 301 and (qty = 0 or CostTotal = 0)) 		
            group by PtypeId
	end                    
	
	if @Displaymode = 1 
	begin	        
			select PtypeId,case when (detailtype > 200 and detailtype < 300) then -SUM(Qty) else SUM(Qty) end as qty,
					case when (detailtype > 200 and detailtype < 300) then -SUM(CostTotal) else SUM(CostTotal) end as costtotal,	detailtype,
						CASE WHEN (detailtype > 200 and detailtype < 300) THEN -sum(RetailTotal) ELSE sum(RetailTotal) END as RetailTotal into #TempAllJXC2 from 
				(select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	detailtype,
						ROUND(CONVERT(NUMERIC(24,10),SUM(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as RetailTotal from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate between @DateBegin and @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,PtypeId
				union all
				select PtypeId,-SUM(Qty) as qty,-SUM(CostTotal) as costtotal,	401,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),-Qty)*CONVERT(NUMERIC(24,10),c.RetailPrice))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate > @DateEnd
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by DetailType,PtypeId
				union all
				select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	301,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
				where Datadate < @DateBegin
				--and 
				--exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId
				union all (select Ptypeid,SUM(qty) as qty,SUM(total) as costtotal,301 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from IniGoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId)
				union all (select Ptypeid,SUM(qty) as qty,SUM(total) as costtotal,401 as detialtype,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) as retailtotal from GoodsStocks a 
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
					inner join #AllJXCKtypeIdTable b on a.ktypeid = b.KtypeId						
						--where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId)							
				) a
				group by PtypeId,DetailType
			
				
            select  PtypeId ,
		    --(SELECT TOP 1 [Order] FROM [dbo].[Size] si WHERE right('00000' + CAST(si.SizeId as VARCHAR), 5)  = pstypeid ) AS psOrder , 
                    isnull(sum(case DetailType
                                 when 101 then Qty
                                 else 0
                               end), 0) as Qty101 ,
                    isnull(sum(case DetailType
                                 when 101 then CostTotal
                                 else 0
                               end), 0) as Total101 ,
                    isnull(sum(case DetailType
                                 when 101 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal101 ,
                    isnull(sum(case DetailType
                                 when 102 then Qty
                                 else 0
                               end), 0) as Qty102 ,
                    isnull(sum(case DetailType
                                 when 102 then CostTotal
                                 else 0
                               end), 0) as Total102 ,
                    isnull(sum(case DetailType
                                 when 102 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal102 ,
                    isnull(sum(case DetailType
                                 when 103 then Qty
                                 else 0
                               end), 0) as Qty103 ,
                    isnull(sum(case DetailType
                                 when 103 then CostTotal
                                 else 0
                               end), 0) as Total103 ,
                    isnull(sum(case DetailType
                                 when 103 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal103 ,
                    isnull(sum(case DetailType
                                 when 104 then Qty
                                 else 0
                               end), 0) as Qty104 ,
                    isnull(sum(case DetailType
                                 when 104 then CostTotal
                                 else 0
                               end), 0) as Total104 ,
                    isnull(sum(case DetailType
                                 when 104 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal104 ,
                    isnull(sum(case DetailType
                                 when 105 then Qty
                                 else 0
                               end), 0) as Qty105 ,
                    isnull(sum(case DetailType
                                 when 105 then CostTotal
                                 else 0
                               end), 0) as Total105 ,
                    isnull(sum(case DetailType
                                 when 105 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal105 ,
                    isnull(sum(case DetailType
                                 when 106 then Qty
                                 else 0
                               end), 0) as Qty106 ,
                    isnull(sum(case DetailType
                                 when 106 then CostTotal
                                 else 0
                               end), 0) as Total106 ,
                    isnull(sum(case DetailType
                                 when 106 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal106 ,
                    isnull(sum(case DetailType
                                 when 107 then Qty
                                 else 0
                               end), 0) as Qty107 ,
                    isnull(sum(case DetailType
                                 when 107 then CostTotal
                                 else 0
                               end), 0) as Total107 ,
                    isnull(sum(case DetailType
                                 when 107 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal107 ,
                    isnull(sum(case DetailType
                                 when 108 then Qty
                                 else 0
                               end), 0) as Qty108 ,
                    isnull(sum(case DetailType
                                 when 108 then CostTotal
                                 else 0
                               end), 0) as Total108 ,
                    isnull(sum(case DetailType
                                 when 108 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal108 ,
                    isnull(sum(case DetailType
                                 when 109 then Qty
                                 else 0
                               end), 0) as Qty109 ,
                    isnull(sum(case DetailType
                                 when 109 then CostTotal
                                 else 0
                               end), 0) as Total109 ,
                    isnull(sum(case DetailType
                                 when 109 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal109 ,
                    isnull(sum(case DetailType
                                 when 110 then Qty
                                 else 0
                               end), 0) as Qty110 ,
                    isnull(sum(case DetailType
                                 when 110 then CostTotal
                                 else 0
                               end), 0) as Total110 ,
                    isnull(sum(case DetailType
                                 when 110 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal110 ,
                    isnull(sum(case DetailType
                                 when 112 then Qty
                                 else 0
                               end), 0) as Qty112 ,
                    isnull(sum(case DetailType
                                 when 112 then CostTotal
                                 else 0
                               end), 0) as Total112 ,
                    isnull(sum(case DetailType
                                 when 112 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal112 ,
                    isnull(sum(case DetailType
                                 when 113 then Qty
                                 else 0
                               end), 0) as Qty113 ,
                    isnull(sum(case DetailType
                                 when 113 then CostTotal
                                 else 0
                               end), 0) as Total113 ,
                    isnull(sum(case DetailType
                                 when 113 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal113 ,
                    isnull(sum(case DetailType
                                 when 114 then Qty
                                 else 0
                               end), 0) as Qty114 ,
                    isnull(sum(case DetailType
                                 when 114 then CostTotal
                                 else 0
                               end), 0) as Total114 ,
                    isnull(sum(case DetailType
                                 when 114 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal114 ,
                    isnull(sum(case DetailType
                                 when 115 then Qty
                                 else 0
                               end), 0) as Qty115 ,
                    isnull(sum(case DetailType
                                 when 115 then CostTotal
                                 else 0
                               end), 0) as Total115 ,
                    isnull(sum(case DetailType
                                 when 115 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal115 ,
                    isnull(sum(case DetailType
                                 when 116 then Qty
                                 else 0
                               end), 0) as Qty116 ,
                    isnull(sum(case DetailType
                                 when 116 then CostTotal
                                 else 0
                               end), 0) as Total116 ,
                    isnull(sum(case DetailType
                                 when 116 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal116 ,
                    isnull(sum(case DetailType
                                 when 118 then Qty
                                 else 0
                               end), 0) as Qty118 ,
                    isnull(sum(case DetailType
                                 when 118 then CostTotal
                                 else 0
                               end), 0) as Total118 ,
                    isnull(sum(case DetailType
                                 when 118 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal118 ,
                    isnull(sum(case DetailType
                                 when 120 then Qty
                                 else 0
                               end), 0) as Qty120 ,
                    isnull(sum(case DetailType
                                 when 120 then CostTotal
                                 else 0
                               end), 0) as Total120 ,
                    isnull(sum(case DetailType
                                 when 120 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal120 ,
                    isnull(sum(case DetailType
                                 when 121 then Qty
                                 else 0
                               end), 0) as Qty121 ,
                    isnull(sum(case DetailType
                                 when 121 then CostTotal
                                 else 0
                               end), 0) as Total121 ,
                    isnull(sum(case DetailType
                                 when 121 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal121 ,
                    isnull(sum(case DetailType
                                 when 201 then Qty
                                 else 0
                               end), 0) as Qty201 ,
                    isnull(sum(case DetailType
                                 when 201 then CostTotal
                                 else 0
                               end), 0) as Total201 ,
                    isnull(sum(case DetailType
                                 when 201 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal201 ,
                    isnull(sum(case DetailType
                                 when 202 then Qty
                                 else 0
                               end), 0) as Qty202 ,
                    isnull(sum(case DetailType
                                 when 202 then CostTotal
                                 else 0
                               end), 0) as Total202 ,
                    isnull(sum(case DetailType
                                 when 202 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal202 ,
                    isnull(sum(case DetailType
                                 when 203 then Qty
                                 else 0
                               end), 0) as Qty203 ,
                    isnull(sum(case DetailType
                                 when 203 then CostTotal
                                 else 0
                               end), 0) as Total203 ,
                    isnull(sum(case DetailType
                                 when 203 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal203 ,
                    isnull(sum(case DetailType
                                 when 204 then Qty
                                 else 0
                               end), 0) as Qty204 ,
                    isnull(sum(case DetailType
                                 when 204 then CostTotal
                                 else 0
                               end), 0) as Total204 ,
                    isnull(sum(case DetailType
                                 when 204 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal204 ,
                    isnull(sum(case DetailType
                                 when 205 then Qty
                                 else 0
                               end), 0) as Qty205 ,
                    isnull(sum(case DetailType
                                 when 205 then CostTotal
                                 else 0
                               end), 0) as Total205 ,
                    isnull(sum(case DetailType
                                 when 205 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal205 ,
                    isnull(sum(case DetailType
                                 when 206 then Qty
                                 else 0
                               end), 0) as Qty206 ,
                    isnull(sum(case DetailType
                                 when 206 then CostTotal
                                 else 0
                               end), 0) as Total206 ,
                    isnull(sum(case DetailType
                                 when 206 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal206 ,
                    isnull(sum(case DetailType
                                 when 207 then Qty
                                 else 0
                               end), 0) as Qty207 ,
                    isnull(sum(case DetailType
                                 when 207 then CostTotal
                                 else 0
                               end), 0) as Total207 ,
                    isnull(sum(case DetailType
                                 when 207 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal207 ,
                    isnull(sum(case DetailType
                                 when 208 then Qty
                                 else 0
                               end), 0) as Qty208 ,
                    isnull(sum(case DetailType
                                 when 208 then CostTotal
                                 else 0
                               end), 0) as Total208 ,
                    isnull(sum(case DetailType
                                 when 208 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal208 ,
                    isnull(sum(case DetailType
                                 when 209 then Qty
                                 else 0
                               end), 0) as Qty209 ,
                    isnull(sum(case DetailType
                                 when 209 then CostTotal
                                 else 0
                               end), 0) as Total209 ,
                    isnull(sum(case DetailType
                                 when 209 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal209 ,
                    isnull(sum(case DetailType
                                 when 210 then Qty
                                 else 0
                               end), 0) as Qty210 ,
                    isnull(sum(case DetailType
                                 when 210 then CostTotal
                                 else 0
                               end), 0) as Total210 ,
                    isnull(sum(case DetailType
                                 when 210 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal210 ,
                    isnull(sum(case DetailType
                                 when 212 then Qty
                                 else 0
                               end), 0) as Qty212 ,
                    isnull(sum(case DetailType
                                 when 212 then CostTotal
                                 else 0
                               end), 0) as Total212 ,
                    isnull(sum(case DetailType
                                 when 212 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal212 ,
                    isnull(sum(case DetailType
                                 when 213 then Qty
                                 else 0
                               end), 0) as Qty213 ,
                    isnull(sum(case DetailType
                                 when 213 then CostTotal
                                 else 0
                               end), 0) as Total213 ,
                    isnull(sum(case DetailType
                                 when 213 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal213 ,
                    isnull(sum(case DetailType
                                 when 214 then Qty
                                 else 0
                               end), 0) as Qty214 ,
                    isnull(sum(case DetailType
                                 when 214 then CostTotal
                                 else 0
                               end), 0) as Total214 ,
                    isnull(sum(case DetailType
                                 when 214 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal214 ,
                    isnull(sum(case DetailType
                                 when 215 then Qty
                                 else 0
                               end), 0) as Qty215 ,
                    isnull(sum(case DetailType
                                 when 215 then CostTotal
                                 else 0
                               end), 0) as Total215 ,
                    isnull(sum(case DetailType
                                 when 215 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal215 ,
                    isnull(sum(case DetailType
                                 when 216 then Qty
                                 else 0
                               end), 0) as Qty216 ,
                    isnull(sum(case DetailType
                                 when 216 then CostTotal
                                 else 0
                               end), 0) as Total216 ,
                    isnull(sum(case DetailType
                                 when 216 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal216 ,
                    isnull(sum(case DetailType
                                 when 218 then Qty
                                 else 0
                               end), 0) as Qty218 ,
                    isnull(sum(case DetailType
                                 when 218 then CostTotal
                                 else 0
                               end), 0) as Total218 ,
                    isnull(sum(case DetailType
                                 when 218 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal218 ,
                    isnull(sum(case DetailType
                                 when 220 then Qty
                                 else 0
                               end), 0) as Qty220 ,
                    isnull(sum(case DetailType
                                 when 220 then CostTotal
                                 else 0
                               end), 0) as Total220 ,
                    isnull(sum(case DetailType
                                 when 220 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal220 ,
                    isnull(sum(case DetailType
                                 when 221 then Qty
                                 else 0
                               end), 0) as Qty221 ,
                    isnull(sum(case DetailType
                                 when 221 then CostTotal
                                 else 0
                               end), 0) as Total221 ,
                    isnull(sum(case DetailType
                                 when 221 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal221 ,
                    isnull(sum(case DetailType
                                 when 301 then Qty
                                 else 0
                               end), 0) as Qty301 ,
                    isnull(sum(case DetailType
                                 when 301 then CostTotal
                                 else 0
                               end), 0) as Total301 ,
                    isnull(sum(case DetailType
                                 when 301 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal301 ,
                    isnull(sum(case DetailType
                                 when 401 then Qty
                                 else 0
                               end), 0) as Qty401 ,
                    isnull(sum(case DetailType
                                 when 401 then CostTotal
                                 else 0
                               end), 0) as Total401 ,
                    isnull(sum(case DetailType
                                 when 401 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal401
            from    #TempAllJXC2 a --where not (DetailType = 301 and (qty = 0 or CostTotal = 0)) 
            group by PtypeId
	end                    
			
	if @Displaymode = 2 
	begin	        
				
			select PtypeId,case when (detailtype > 200 and detailtype < 300) then -SUM(Qty) else SUM(Qty) end as qty,
					case when (detailtype > 200 and detailtype < 300) then -SUM(CostTotal) else SUM(CostTotal) end as costtotal,	detailtype,ColorId,SizeId,
						CASE WHEN (detailtype > 200 and detailtype < 300) THEN -sum(RetailTotal) ELSE sum(RetailTotal) END as RetailTotal into #TempAllJXC3 from 
				(			select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,DetailType,ColorId,SizeId,ROUND(CONVERT(NUMERIC(24,10),sum(c.RetailPrice*qty)),@dig_total) as retailtotal from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				where Datadate between @DateBegin and @DateEnd
				and exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId,ColorId,SizeId,DetailType
				union all
				select PtypeId,-SUM(Qty) as qty,-SUM(CostTotal) as costtotal,	401,ColorId,SizeId,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),-Qty)*CONVERT(NUMERIC(24,10),c.RetailPrice))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				where Datadate > @DateEnd
				and 
				exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId,ColorId,SizeId,DetailType
				union all
				select PtypeId,SUM(Qty) as qty,SUM(CostTotal) as costtotal,	301,ColorId,SizeId,
						ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),Qty))),@dig_total) from TableForAllJXC a
				inner join #AllJXCPtypeIdTable c on a.ptypeid = c.TypeID
				where Datadate < @DateBegin
				and 
				exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
				--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
				group by PtypeId,ColorId,SizeId
				union all (select Ptypeid,SUM(d.qty) as qty,SUM(d.total) as costtotal,301 as detialtype,d.ColorId,d.SizeId,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),d.Qty))),@dig_total) as retailtotal from IniGoodsStocks a inner join IniGoodsDetail d on a.OrderId = d.OrderId
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
						where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId,ColorId,SizeId)
				union all (select Ptypeid,SUM(d.qty) as qty,SUM(d.total) as costtotal,401 as detialtype,d.ColorId,d.SizeId,
				ROUND(CONVERT(NUMERIC(24,10),sum(CONVERT(NUMERIC(24,10),c.RetailPrice)*CONVERT(NUMERIC(24,10),d.Qty))),@dig_total) as retailtotal from GoodsStocks a inner join Goodsstockdetail d on a.OrderId = d.OrderId
					inner join 
						#AllJXCPtypeIdTable c on a.ptypeid = c.TypeID 
						where exists(select 1 from #AllJXCKtypeIdTable b where a.ktypeid = b.KtypeId)
					--and exists(select 1 from #AllJXCPtypeIdTable c where a.ptypeid = c.TypeID)	
					group by PtypeId,ColorId,SizeId)							
				) a
				group by PtypeId,DetailType,colorid,sizeid
				
				
            select  PtypeId ,
                    Right('00000' + cast(colorid as varchar),5) as pctypeid ,
                    Right('00000' + cast(sizeid as varchar),5) as pstypeid ,
		    --(SELECT TOP 1 [Order] FROM [dbo].[Size] si WHERE right('00000' + CAST(si.SizeId as VARCHAR), 5)  = pstypeid ) AS psOrder , 
                    isnull(sum(case DetailType
                                 when 101 then Qty
                                 else 0
                               end), 0) as Qty101 ,
                    isnull(sum(case DetailType
                                 when 101 then CostTotal
                                 else 0
                               end), 0) as Total101 ,
                    isnull(sum(case DetailType
                                 when 101 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal101 ,
                    isnull(sum(case DetailType
                                 when 102 then Qty
                                 else 0
                               end), 0) as Qty102 ,
                    isnull(sum(case DetailType
                                 when 102 then CostTotal
                                 else 0
                               end), 0) as Total102 ,
                    isnull(sum(case DetailType
                                 when 102 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal102 ,
                    isnull(sum(case DetailType
                                 when 103 then Qty
                                 else 0
                               end), 0) as Qty103 ,
                    isnull(sum(case DetailType
                                 when 103 then CostTotal
                                 else 0
                               end), 0) as Total103 ,
                    isnull(sum(case DetailType
                                 when 103 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal103 ,
                    isnull(sum(case DetailType
                                 when 104 then Qty
                                 else 0
                               end), 0) as Qty104 ,
                    isnull(sum(case DetailType
                                 when 104 then CostTotal
                                 else 0
                               end), 0) as Total104 ,
                    isnull(sum(case DetailType
                                 when 104 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal104 ,
                    isnull(sum(case DetailType
                                 when 105 then Qty
                                 else 0
                               end), 0) as Qty105 ,
                    isnull(sum(case DetailType
                                 when 105 then CostTotal
                                 else 0
                               end), 0) as Total105 ,
                    isnull(sum(case DetailType
                                 when 105 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal105 ,
                    isnull(sum(case DetailType
                                 when 106 then Qty
                                 else 0
                               end), 0) as Qty106 ,
                    isnull(sum(case DetailType
                                 when 106 then CostTotal
                                 else 0
                               end), 0) as Total106 ,
                    isnull(sum(case DetailType
                                 when 106 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal106 ,
                    isnull(sum(case DetailType
                                 when 107 then Qty
                                 else 0
                               end), 0) as Qty107 ,
                    isnull(sum(case DetailType
                                 when 107 then CostTotal
                                 else 0
                               end), 0) as Total107 ,
                    isnull(sum(case DetailType
                                 when 107 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal107 ,
                    isnull(sum(case DetailType
                                 when 108 then Qty
                                 else 0
                               end), 0) as Qty108 ,
                    isnull(sum(case DetailType
                                 when 108 then CostTotal
                                 else 0
                               end), 0) as Total108 ,
                    isnull(sum(case DetailType
                                 when 108 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal108 ,
                    isnull(sum(case DetailType
                                 when 109 then Qty
                                 else 0
                               end), 0) as Qty109 ,
                    isnull(sum(case DetailType
                                 when 109 then CostTotal
                                 else 0
                               end), 0) as Total109 ,
                    isnull(sum(case DetailType
                                 when 109 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal109 ,
                    isnull(sum(case DetailType
                                 when 110 then Qty
                                 else 0
                               end), 0) as Qty110 ,
                    isnull(sum(case DetailType
                                 when 110 then CostTotal
                                 else 0
                               end), 0) as Total110 ,
                    isnull(sum(case DetailType
                                 when 110 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal110 ,
                    isnull(sum(case DetailType
                                 when 112 then Qty
                                 else 0
                               end), 0) as Qty112 ,
                    isnull(sum(case DetailType
                                 when 112 then CostTotal
                                 else 0
                               end), 0) as Total112 ,
                    isnull(sum(case DetailType
                                 when 112 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal112 ,
                    isnull(sum(case DetailType
                                 when 113 then Qty
                                 else 0
                               end), 0) as Qty113 ,
                    isnull(sum(case DetailType
                                 when 113 then CostTotal
                                 else 0
                               end), 0) as Total113 ,
                    isnull(sum(case DetailType
                                 when 113 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal113 ,
                    isnull(sum(case DetailType
                                 when 114 then Qty
                                 else 0
                               end), 0) as Qty114 ,
                    isnull(sum(case DetailType
                                 when 114 then CostTotal
                                 else 0
                               end), 0) as Total114 ,
                    isnull(sum(case DetailType
                                 when 114 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal114 ,
                    isnull(sum(case DetailType
                                 when 115 then Qty
                                 else 0
                               end), 0) as Qty115 ,
                    isnull(sum(case DetailType
                                 when 115 then CostTotal
                                 else 0
                               end), 0) as Total115 ,
                    isnull(sum(case DetailType
                                 when 115 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal115 ,
                    isnull(sum(case DetailType
                                 when 116 then Qty
                                 else 0
                               end), 0) as Qty116 ,
                    isnull(sum(case DetailType
                                 when 116 then CostTotal
                                 else 0
                               end), 0) as Total116 ,
                    isnull(sum(case DetailType
                                 when 116 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal116 ,
                    isnull(sum(case DetailType
                                 when 118 then Qty
                                 else 0
                               end), 0) as Qty118 ,
                    isnull(sum(case DetailType
                                 when 118 then CostTotal
                                 else 0
                               end), 0) as Total118 ,
                    isnull(sum(case DetailType
                                 when 118 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal118 ,
                    isnull(sum(case DetailType
                                 when 120 then Qty
                                 else 0
                               end), 0) as Qty120 ,
                    isnull(sum(case DetailType
                                 when 120 then CostTotal
                                 else 0
                               end), 0) as Total120 ,
                    isnull(sum(case DetailType
                                 when 120 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal120 ,
                    isnull(sum(case DetailType
                                 when 121 then Qty
                                 else 0
                               end), 0) as Qty121 ,
                    isnull(sum(case DetailType
                                 when 121 then CostTotal
                                 else 0
                               end), 0) as Total121 ,
                    isnull(sum(case DetailType
                                 when 121 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal121 ,
                    isnull(sum(case DetailType
                                 when 201 then Qty
                                 else 0
                               end), 0) as Qty201 ,
                    isnull(sum(case DetailType
                                 when 201 then CostTotal
                                 else 0
                               end), 0) as Total201 ,
                    isnull(sum(case DetailType
                                 when 201 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal201 ,
                    isnull(sum(case DetailType
                                 when 202 then Qty
                                 else 0
                               end), 0) as Qty202 ,
                    isnull(sum(case DetailType
                                 when 202 then CostTotal
                                 else 0
                               end), 0) as Total202 ,
                    isnull(sum(case DetailType
                                 when 202 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal202 ,
                    isnull(sum(case DetailType
                                 when 203 then Qty
                                 else 0
                               end), 0) as Qty203 ,
                    isnull(sum(case DetailType
                                 when 203 then CostTotal
                                 else 0
                               end), 0) as Total203 ,
                    isnull(sum(case DetailType
                                 when 203 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal203 ,
                    isnull(sum(case DetailType
                                 when 204 then Qty
                                 else 0
                               end), 0) as Qty204 ,
                    isnull(sum(case DetailType
                                 when 204 then CostTotal
                                 else 0
                               end), 0) as Total204 ,
                    isnull(sum(case DetailType
                                 when 204 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal204 ,
                    isnull(sum(case DetailType
                                 when 205 then Qty
                                 else 0
                               end), 0) as Qty205 ,
                    isnull(sum(case DetailType
                                 when 205 then CostTotal
                                 else 0
                               end), 0) as Total205 ,
                    isnull(sum(case DetailType
                                 when 205 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal205 ,
                    isnull(sum(case DetailType
                                 when 206 then Qty
                                 else 0
                               end), 0) as Qty206 ,
                    isnull(sum(case DetailType
                                 when 206 then CostTotal
                                 else 0
                               end), 0) as Total206 ,
                    isnull(sum(case DetailType
                                 when 206 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal206 ,
                    isnull(sum(case DetailType
                                 when 207 then Qty
                                 else 0
                               end), 0) as Qty207 ,
                    isnull(sum(case DetailType
                                 when 207 then CostTotal
                                 else 0
                               end), 0) as Total207 ,
                    isnull(sum(case DetailType
                                 when 207 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal207 ,
                    isnull(sum(case DetailType
                                 when 208 then Qty
                                 else 0
                               end), 0) as Qty208 ,
                    isnull(sum(case DetailType
                                 when 208 then CostTotal
                                 else 0
                               end), 0) as Total208 ,
                    isnull(sum(case DetailType
                                 when 208 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal208 ,
                    isnull(sum(case DetailType
                                 when 209 then Qty
                                 else 0
                               end), 0) as Qty209 ,
                    isnull(sum(case DetailType
                                 when 209 then CostTotal
                                 else 0
                               end), 0) as Total209 ,
                    isnull(sum(case DetailType
                                 when 209 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal209 ,
                    isnull(sum(case DetailType
                                 when 210 then Qty
                                 else 0
                               end), 0) as Qty210 ,
                    isnull(sum(case DetailType
                                 when 210 then CostTotal
                                 else 0
                               end), 0) as Total210 ,
                    isnull(sum(case DetailType
                                 when 210 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal210 ,
                    isnull(sum(case DetailType
                                 when 212 then Qty
                                 else 0
                               end), 0) as Qty212 ,
                    isnull(sum(case DetailType
                                 when 212 then CostTotal
                                 else 0
                               end), 0) as Total212 ,
                    isnull(sum(case DetailType
                                 when 212 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal212 ,
                    isnull(sum(case DetailType
                                 when 213 then Qty
                                 else 0
                               end), 0) as Qty213 ,
                    isnull(sum(case DetailType
                                 when 213 then CostTotal
                                 else 0
                               end), 0) as Total213 ,
                    isnull(sum(case DetailType
                                 when 213 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal213 ,
                    isnull(sum(case DetailType
                                 when 214 then Qty
                                 else 0
                               end), 0) as Qty214 ,
                    isnull(sum(case DetailType
                                 when 214 then CostTotal
                                 else 0
                               end), 0) as Total214 ,
                    isnull(sum(case DetailType
                                 when 214 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal214 ,
                    isnull(sum(case DetailType
                                 when 215 then Qty
                                 else 0
                               end), 0) as Qty215 ,
                    isnull(sum(case DetailType
                                 when 215 then CostTotal
                                 else 0
                               end), 0) as Total215 ,
                    isnull(sum(case DetailType
                                 when 215 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal215 ,
                    isnull(sum(case DetailType
                                 when 216 then Qty
                                 else 0
                               end), 0) as Qty216 ,
                    isnull(sum(case DetailType
                                 when 216 then CostTotal
                                 else 0
                               end), 0) as Total216 ,
                    isnull(sum(case DetailType
                                 when 216 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal216 ,
                    isnull(sum(case DetailType
                                 when 218 then Qty
                                 else 0
                               end), 0) as Qty218 ,
                    isnull(sum(case DetailType
                                 when 218 then CostTotal
                                 else 0
                               end), 0) as Total218 ,
                    isnull(sum(case DetailType
                                 when 218 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal218 ,
                    isnull(sum(case DetailType
                                 when 220 then Qty
                                 else 0
                               end), 0) as Qty220 ,
                    isnull(sum(case DetailType
                                 when 220 then CostTotal
                                 else 0
                               end), 0) as Total220 ,
                    isnull(sum(case DetailType
                                 when 220 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal220 ,
                    isnull(sum(case DetailType
                                 when 221 then Qty
                                 else 0
                               end), 0) as Qty221 ,
                    isnull(sum(case DetailType
                                 when 221 then CostTotal
                                 else 0
                               end), 0) as Total221 ,
                    isnull(sum(case DetailType
                                 when 221 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal221 ,
                    isnull(sum(case DetailType
                                 when 301 then Qty
                                 else 0
                               end), 0) as Qty301 ,
                    isnull(sum(case DetailType
                                 when 301 then CostTotal
                                 else 0
                               end), 0) as Total301 ,
                    isnull(sum(case DetailType
                                 when 301 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal301 ,
                    isnull(sum(case DetailType
                                 when 401 then Qty
                                 else 0
                               end), 0) as Qty401 ,
                    isnull(sum(case DetailType
                                 when 401 then CostTotal
                                 else 0
                               end), 0) as Total401 ,
                    isnull(sum(case DetailType
                                 when 401 then RetailTotal
                                 else 0
                               end), 0) as RetailTotal401
            from    #TempAllJXC3 a --where not (DetailType = 301 and (qty = 0 or CostTotal = 0)) 
		
            group by PtypeId ,
                    ColorId ,
                    SizeId	
	end                    
    if object_id('tempdb..#AllJXCKtypeIdTable') is not null 
        drop table #AllJXCKtypeIdTable
    if object_id('tempdb..#AllJXCPtypeIdTable') is not null 
        drop table #AllJXCPtypeIdTable        
    if object_id('tempdb..#TempAllJXC1') is not null 
        drop table #TempAllJXC1       
    if object_id('tempdb..#TempAllJXC2') is not null 
        drop table #TempAllJXC2       
    if object_id('tempdb..#TempAllJXC2q') is not null 
        drop table #TempAllJXC2q                      
    if object_id('tempdb..#TempAllJXC3') is not null 
        drop table #TempAllJXC3                               
        
end                            




GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZGetCurrentTotal]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
  DROP PROCEDURE [dbo].[FZGetCurrentTotal]
GO




--取得在某一个时间一个或一类商品的库存，一个单位的应收余额，一个科目的余额
CREATE  PROCEDURE FZGetCurrentTotal
(
 @szSelect VARCHAR(50),
 @szAtypeid VARCHAR(50),
 @szPtypeid VARCHAR(50),
 @szBtypeid VARCHAR(50),
 @szEtypeid VARCHAR(50),
 @szKtypeid VARCHAR(50),
 @Enddate VARCHAR(10),
 @dQty NUMERIC(24, 10) OUTPUT,
 @dTotal NUMERIC(24, 10) OUTPUT,
 @BranchId VARCHAR(50),
 @OperatorId VARCHAR(50),
 @IsStop BIT = 0,--是否包含停用商品 0：包含  1：不包含
 @includeYS BIT = 0 ,	--是否包含预收款 ：1包含 0不包含
 @includeYF BIT = 0	--是否包含预付款 ：1包含 0不包含    
)
AS 
DECLARE @AR_ID VARCHAR(50)
DECLARE @AP_ID VARCHAR(50)
DECLARE @dTempAr NUMERIC(24, 10)
DECLARE @dTempAp NUMERIC(24, 10),
	@PreAr NUMERIC(24, 10),
	@PreAp NUMERIC(24, 10),
	@FZCS int
DECLARE @nPSon INT
DECLARE @nBSon INT
SELECT  @AR_ID = '0000100005'
SELECT  @AP_ID = '0000200001'

IF EXISTS(SELECT * FROM sysdata WHERE SubName = 'proctypename' AND SubValue = 'FZCS')
SELECT @FZCS = 1
ELSE SELECT @FZCS = 0
    
IF @szSelect = 'btype' 
  BEGIN
    SELECT  @nBSon = [sonnum]
    FROM    btype
    WHERE   [typeid] = (CASE @szBtypeid
                          WHEN '' THEN '00000'
                          ELSE @szBtypeid
                        END)
    IF @nBSon > 0 
      BEGIN
        SELECT  @dTotal = ISNULL(SUM(CASE atypeid WHEN '0000200888' THEN -total ELSE total end), 0)
        FROM    dlya
        WHERE   [date] >= @Enddate AND RedOld = 'F'
                AND btypeid LIKE @szBtypeid + '%'
                AND ((atypeid = @AR_ID AND @includeYS = 0) OR ((atypeid = @AR_ID OR atypeid = '0000200888') AND @includeYS = 1))
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = dlya.branchid ))
                	OR
                	(@FZCS = 1 AND dlya.branchid LIKE @BranchId + '%')
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = dlya.BranchID
                                    AND iniover = 1 )
                            
        SELECT  @dQty = ISNULL(SUM(CASE atypeid WHEN '0000100888' THEN -total ELSE total end), 0)
        FROM    dlya
        WHERE   [date] >= @Enddate AND RedOld = 'F'
                AND btypeid LIKE @szBtypeid + '%'
                AND ((atypeid = @Ap_ID AND @includeYF = 0) OR ((atypeid = @Ap_ID OR atypeid = '0000100888') AND @includeYF = 1))
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = dlya.branchid ))
                	OR
                	(@FZCS = 1 AND dlya.branchid LIKE @BranchId + '%')
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = dlya.BranchID
                                    AND iniover = 1 )
                            
        SELECT  @dTotal = @dTotal - @dQty
        SELECT  @dTempAr = ISNULL(SUM(bb.artotal), 0),
                @dTempAp = ISNULL(SUM(bb.aptotal), 0),
                @PreAr = SUM(ISNULL(bb.deposit,0)),
                @PreAp = SUM(ISNULL(bb.prepayment,0))
                --SELECT * FROM dbo.BranchBtype
        FROM    btype b
        LEFT JOIN BranchBtype bb
        ON      b.TypeId = bb.Btypeid
                AND bb.BranchId LIKE @BranchID + '%'
        WHERE   b.typeid LIKE @szBtypeid + '%'
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = bb.branchid ))
                	OR
                	(@FZCS = 1 AND 1=1)
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = bb.BranchID
                                    AND iniover = 1 )
          
        SELECT  @dTotal = (@dTempAr - @dTempAp) - @dTotal
        IF   @includeYF = 1 SELECT @dTotal = @dTotal + @PreAp
        IF   @includeYS = 1 SELECT @dTotal = @dTotal - @PreAr
        SELECT  @dQty = @dTotal
        RETURN 0
      END
    ELSE 
      BEGIN
        SELECT  @dTotal = ISNULL(SUM(CASE atypeid WHEN '0000200888' THEN -total ELSE total end), 0)
        FROM    dlya
        WHERE   [date] >= @Enddate AND RedOld = 'F'
                AND btypeid = @szBtypeid
                AND ((atypeid = @AR_ID AND @includeYF = 0) OR ((atypeid = @AR_ID OR atypeid = '0000200888') AND @includeYF = 1))
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = dlya.branchid ))
                	OR
                	(@FZCS = 1 AND dlya.branchid LIKE @BranchId + '%')
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = dlya.BranchID
                                    AND iniover = 1 )
                            
        SELECT  @dQty = ISNULL(SUM(CASE atypeid WHEN '0000100888' THEN -total ELSE total end), 0)
        FROM    dlya
        WHERE   [date] >= @Enddate AND RedOld = 'F'
                AND btypeid = @szBtypeid
                AND ((atypeid = @Ap_ID AND @includeYF = 0) OR ((atypeid = @Ap_ID OR atypeid = '0000100888') AND @includeYF = 1))
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = dlya.branchid ))
                	OR
                	(@FZCS = 1 AND dlya.branchid LIKE @BranchId + '%')
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = dlya.BranchID
                                    AND iniover = 1 )
                            
        SELECT  @dTotal = @dTotal - @dQty
        SELECT  @dTempAr = ISNULL(SUM(bb.artotal), 0),
                @dTempAp = ISNULL(SUM(bb.aptotal), 0),
                @PreAr = SUM(ISNULL(bb.deposit,0)),
                @PreAp = SUM(ISNULL(bb.prepayment,0))
        FROM    btype b
        LEFT JOIN BranchBtype bb
        ON      b.TypeId = bb.Btypeid
                AND bb.BranchId LIKE @BranchID + '%'
        WHERE   b.typeid = @szBtypeid
                AND (
                	(@FZCS = 0 AND EXISTS ( SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorID,@BranchId) WHERE  BranchID = bb.branchid ))
                	OR
                	(@FZCS = 1 AND 1=1)
                    )
                AND EXISTS ( SELECT 1
                             FROM   branch
                             WHERE  branchid = bb.BranchID
                                    AND iniover = 1 )
                            
        SELECT  @dTotal = (@dTempAr - @dTempAp) - @dTotal
        IF   @includeYF = 1 SELECT @dTotal = @dTotal + @PreAp
        IF   @includeYS = 1 SELECT @dTotal = @dTotal - @PreAr
        SELECT  @dQty = @dTotal
        RETURN 0
      END
  END
-------------------------------------------------------
IF @szSelect = 'etype' 
  BEGIN
    SELECT  @nBSon = [sonnum]
    FROM    employee
    WHERE   [typeid] = @szEtypeid
    IF @nBSon > 0
      AND @szEtypeid <> '00000' 
      BEGIN
        SELECT  @dTotal = SUM(ISNULL(total, 0))
        FROM    dlya
        WHERE   [date] <= @Enddate AND RedOld = 'F'
                AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                AND atypeid IN (@AR_ID, @AP_ID)  
        SELECT  @dQty = SUM(ISNULL(total, 0))
        FROM    dlya
        WHERE   [date] <= @Enddate AND RedOld = 'F'
                AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                AND atypeid IN (@AR_ID, @AP_ID)
        IF @dQty > 0 
          SELECT  @dTotal = -@dQty

        IF LEFT(@szBtypeid, 5) = '00001'
          AND @szatypeid = '0000200001' --应付
          BEGIN
            SELECT  @dTotal = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000200001'
            SELECT  @dTempAp = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000100005'
            SELECT  @dTempAp = ISNULL(@dTempAp, 0)
            SELECT  @dTotal = -(@dTotal - @dTempAp)

          END
        IF LEFT(@szBtypeid, 5) <> '00001'
          AND @szatypeid = '0000100005' --应收
          BEGIN
            SELECT  @dQty = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000100005'
            SELECT  @dTempAp = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND LEFT([etypeid], LEN(@szEtypeid)) = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000200001'
            SELECT  @dTempAp = ISNULL(@dTempAp, 0)
            SELECT  @dQty = ISNULL(@dQty, 0) - @dTempAp

          END
        IF @dQty <> 0 
          SELECT  @dTotal = @dQty
        SELECT  @dTotal = ISNULL(@dTotal, 0)
        SELECT  @dQty = ISNULL(@dQty, 0)
      END
    ELSE 
      BEGIN
        IF LEFT(@szBtypeid, 5) = '00001'
          AND @szatypeid = '0000200001' --应付
          BEGIN
            SELECT  @dTotal = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND etypeid = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000200001'
            SELECT  @dTempAp = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND etypeid = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000100005'
            SELECT  @dTempAp = ISNULL(@dTempAp, 0)
            SELECT  @dTotal = -(ISNULL(@dTotal, 0) - @dTempAp)

          END
        IF LEFT(@szBtypeid, 5) <> '00001'
          AND @szatypeid = '0000100005' --应收
          BEGIN
            SELECT  @dQty = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND etypeid = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000100005'
            SELECT  @dTempAp = SUM(ISNULL(total, 0))
            FROM    dlya
            WHERE   [date] <= @Enddate AND RedOld = 'F'
                    AND etypeid = @szEtypeid
                    AND LEFT([btypeid], LEN(@szBtypeid)) = @szBtypeid
                    AND atypeid = '0000200001'
            SELECT  @dTempAp = ISNULL(@dTempAp, 0)
            SELECT  @dQty = @dQty - @dTempAp

          END
        IF @dQty <> 0 
          SELECT  @dTotal = @dQty
        SELECT  @dTotal = ISNULL(@dTotal, 0)
        SELECT  @dQty = ISNULL(@dQty, 0)
        RETURN 0
      END
  END
-----------------------------------------------------------
ELSE 
  IF @szSelect = 'ptype' 
    BEGIN
      SELECT  @nPSon = sonnum
      FROM    ptype
      WHERE   typeid = @szPtypeid
      IF @szKtypeid = '00000' 
        SET @szKtypeid = ''
      IF @szBtypeid = '00000' 
        SET @szBtypeid = ''
      IF @szKtypeid <> '00000'
        AND @szKtypeid <> '99999' 
        BEGIN
          IF @nPSon > 0 
            BEGIN
              SELECT  @dQty = ISNULL(SUM(qty), 0),
                      @dTotal = ISNULL(SUM(total), 0)
              FROM    goodsstocks a
              INNER JOIN Ptype p
              ON      a.PtypeId = p.TypeID
              WHERE   EXISTS ( SELECT 1
                               FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                               WHERE  Ktypeid = a.Ktypeid )
                      AND LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                      AND p.Stop IN (CASE @IsStop
                                       WHEN 0 THEN p.stop
                                       ELSE 0
                                     END)--是否包含停用商品

              SELECT  @dTempar = ISNULL(SUM(qty), 0),
                      @dTempap = ISNULL(SUM(costtotal), 0)
              FROM    DlyData a
              INNER JOIN Ptype p
              ON      a.PtypeId = p.TypeID
              WHERE   [date] >= @enddate  AND a.RedOld = 'F'
                      AND EXISTS ( SELECT 1
                                   FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                   WHERE  Ktypeid = a.Ktypeid )
                      AND LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                      AND pdetail <> 2
                      AND Vchtype NOT IN ('73', '89')
                      AND p.Stop IN (CASE @IsStop
                                       WHEN 0 THEN p.stop
                                       ELSE 0
                                     END)--是否包含停用商品
                                        
              SELECT  @dQty = ISNULL(@dQty, 0) - ISNULL(@dTempar, 0)
              SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)
            END
          ELSE 
            BEGIN
              SELECT  @dQty = ISNULL(SUM(qty), 0),
                      @dTotal = ISNULL(SUM(total), 0)
              FROM    goodsstocks a
              WHERE   EXISTS ( SELECT 1
                               FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid) s
                               WHERE  s.Ktypeid = a.Ktypeid )
                      AND ptypeid = @szPtypeid

              SELECT  @dTempar = ISNULL(SUM(qty), 0),
                      @dTempap = ISNULL(SUM(costtotal), 0)
              FROM    DlyData a
              WHERE   [date] >= @enddate AND a.RedOld = 'F'
                      AND EXISTS ( SELECT 1
                                   FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid) s
                                   WHERE  s.Ktypeid = a.Ktypeid )
                      AND ptypeid = @szPtypeid
                      AND pdetail <> 2
                      AND Vchtype NOT IN ('73', '89')
                                                                             
              SELECT  @dQty = ISNULL(@dQTy, 0) - ISNULL(@dTempar, 0)
              SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)
            END
        END
      ELSE 
        IF @szKtypeid <> '99999' 
          BEGIN
            IF @nPSon > 0 
              BEGIN
                SELECT  @dQty = ISNULL(SUM(qty), 0),
                        @dTotal = ISNULL(SUM(total), 0)
                FROM    goodsstocks a
                INNER JOIN Ptype p
                ON      a.PtypeId = p.TypeID
                WHERE   LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                        AND EXISTS ( SELECT 1
                                     FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                     WHERE  Ktypeid = a.Ktypeid )
                        AND p.Stop IN (CASE @IsStop
                                         WHEN 0 THEN p.stop
                                         ELSE 0
                                       END)--是否包含停用商品
                                                                                
                SELECT  @dTempar = ISNULL(SUM(qty), 0),
                        @dTempap = ISNULL(SUM(costtotal), 0)
                FROM    DlyData a
                INNER JOIN Ptype p
                ON      a.PtypeId = p.TypeID
                WHERE   [date] >= @enddate AND a.RedOld = 'F'
                        AND EXISTS ( SELECT 1
                                     FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                     WHERE  Ktypeid = a.Ktypeid )
                        AND LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                        AND pdetail <> 2
                        AND Vchtype NOT IN ('73', '89')
                        AND p.Stop IN (CASE @IsStop
                                         WHEN 0 THEN p.stop
                                         ELSE 0
                                       END)--是否包含停用商品

                SELECT  @dQty = ISNULL(@dQTy, 0) - ISNULL(@dTempar, 0)
                SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)
              END
            ELSE 
              BEGIN
                SELECT  @dQty = ISNULL(SUM(qty), 0),
                        @dTotal = ISNULL(SUM(total), 0)
                FROM    goodsstocks a
                WHERE   ptypeid = @szPtypeid
                        AND EXISTS ( SELECT 1
                                     FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                     WHERE  Ktypeid = a.Ktypeid )
                                                                                        
                SELECT  @dTempar = ISNULL(SUM(qty), 0),
                        @dTempap = ISNULL(SUM(costtotal), 0)
                FROM    DlyData a
                WHERE   [date] >= @enddate AND a.RedOld = 'F'
                        AND ptypeid = @szPtypeid
                        AND pdetail <> 2
                        AND Vchtype NOT IN ('73', '89')
                        AND EXISTS ( SELECT 1
                                     FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                     WHERE  Ktypeid = a.Ktypeid )
                                            
                SELECT  @dQty = ISNULL(@dQTy, 0) - ISNULL(@dTempar, 0)
                SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)
              END
          END
        ELSE 
          IF @szKtypeid = '99999' 
            BEGIN
              IF @nPSon > 0 
                BEGIN

                  SELECT  @dQty = ISNULL(SUM(qty), 0),
                          @dTotal = ISNULL(SUM(total), 0)
                  FROM    goodsstocks a
                  INNER JOIN Ptype p
                  ON      a.PtypeId = p.TypeID
                  WHERE   EXISTS ( SELECT 1
                                   FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                   WHERE  Ktypeid = a.Ktypeid )
                          AND LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                          AND p.Stop IN (CASE @IsStop
                                           WHEN 0 THEN p.stop
                                           ELSE 0
                                         END)--是否包含停用商品
                                                
                  SELECT  @dTempar = ISNULL(SUM(qty), 0),
                          @dTempap = ISNULL(SUM(costtotal), 0)
                  FROM    DlyData a
                  INNER JOIN Ptype p
                  ON      a.PtypeId = p.TypeID
                  WHERE   [date] >= @enddate AND a.RedOld = 'F'
                          AND EXISTS ( SELECT 1
                                       FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                       WHERE  Ktypeid = a.Ktypeid )
                          AND LEFT(ptypeid, LEN(@szPtypeid)) LIKE @szPtypeid
                          AND pdetail <> 2
                          AND Vchtype NOT IN ('73', '89')
                          AND p.Stop IN (CASE @IsStop
                                           WHEN 0 THEN p.stop
                                           ELSE 0
                                         END)--是否包含停用商品
                                                
                  SELECT  @dQty = ISNULL(@dQTy, 0) - ISNULL(@dTempar, 0)
                  SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)
                END
              ELSE 
                BEGIN

                  SELECT  @dQty = ISNULL(SUM(qty), 0),
                          @dTotal = ISNULL(SUM(total), 0)
                  FROM    goodsstocks a
                  WHERE   EXISTS ( SELECT 1
                                   FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                   WHERE  Ktypeid = a.Ktypeid )
                          AND ptypeid = @szPtypeid  
                                                                                                
                  SELECT  @dTempar = ISNULL(SUM(qty), 0),
                          @dTempap = ISNULL(SUM(costtotal), 0)
                  FROM    DlyData a
                  WHERE   [date] >= @enddate AND a.RedOld = 'F'
                          AND EXISTS ( SELECT 1
                                       FROM   FN_GetStockListOfBranch(@OperatorId, @BranchId, @szKtypeid)
                                       WHERE  Ktypeid = a.Ktypeid )
                          AND ptypeid = @szPtypeid
                          AND pdetail <> 2
                          AND Vchtype NOT IN ('73', '89')
                                                                                                
                  SELECT  @dQty = ISNULL(@dQTy, 0) - ISNULL(@dTempar, 0)
                  SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempap, 0)              
                END
            END
      RETURN 0	
    END
  ELSE 
    IF @szSelect = 'atype' 
      BEGIN
        SELECT  @dTotal = ISNULL(SUM(total + TTL00), 0)
        FROM    atype
        WHERE   EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangeBCList(@OperatorId, @BranchId)
                         WHERE  BranchID = atype.branchid )
                AND LEFT(typeid, LEN(@szatypeid)) = @szAtypeID
                            
        SELECT  @dTempar = ISNULL(SUM(total), 0)
        FROM    dlya
        WHERE   EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangeBCList(@OperatorId, @BranchId)
                         WHERE  BranchID = dlya.branchid )
                AND [date] >= @enddate
                AND LEFT(atypeid, LEN(@szatypeid)) = @szAtypeid
                 AND RedOld = 'F'
                            
        SELECT  @dTotal = ISNULL(@dTotal, 0) - ISNULL(@dTempar, 0)
        SELECT  @dQty = ISNULL(@dTotal, 0)
        RETURN 0
      END
    ELSE 
      IF @szSelect = 'employee' 
        BEGIN  
          SELECT  @dTotal = ISNULL(SUM([total]), 0)
          FROM    dlya
          WHERE   [etypeid] = @szEtypeid AND RedOld = 'F'
                  AND [atypeid] = @szAtypeid
                  AND [btypeid] LIKE @szBtypeid + '%'
          SELECT  @dTempar = ISNULL(SUM([total]), 0)
          FROM    dlya
          WHERE   [etypeid] = @szEtypeid AND RedOld = 'F'
                  AND [atypeid] = '0000200001'
                  AND [btypeid] LIKE @szBtypeid + '%'
          SELECT  @dTotal = @dTotal - @dTempar
          SELECT  @dTempar = ISNULL(SUM([total]), 0)
          FROM    dlya
          WHERE   [etypeid] = @szEtypeid AND RedOld = 'F'
                  AND [atypeid] = @szAtypeid
                  AND [btypeid] LIKE @szBtypeid + '%'
                  AND [date] > @Enddate
          SELECT  @dTotal = @dTotal - @dTempar
          SELECT  @dTempar = ISNULL(SUM([total]), 0)
          FROM    dlya
          WHERE   [etypeid] = @szEtypeid AND RedOld = 'F'
                  AND [atypeid] = '0000200001'
                  AND [btypeid] LIKE @szBtypeid + '%'
                  AND [date] > @Enddate
          SELECT  @dTotal = ISNULL(@dTotal, 0) + ISNULL(@dTempar, 0)
          SELECT  @dQty = ISNULL(@dTotal, 0)
          RETURN 0

        END      
      ELSE 
        IF @szSelect = 'send' 
          BEGIN
            SELECT  @dTotal = ISNULL(SUM(tax_total), 0)
            FROM    DlyData
            WHERE   btypeid = @szBtypeid AND RedOld = 'F'
                    AND vchtype IN (23, 29)
                    AND pdetail <> 2
            SELECT  @dQty = ISNULL(SUM(TOTAL), 0)
            FROM    dlya
            WHERE   btypeid = @szBtypeid AND RedOld = 'F'
                    AND vchtype = 24
                    AND (atypeid LIKE '0000100003%'
                         OR atypeid LIKE '0000100004%')
            SELECT  @dTotal = -1 * @dTotal - @dQty
            SELECT  @dQty = ISNULL(SUM(taxtotal), 0)
            FROM    inicommission
            WHERE   btypeid = @szBtypeid
                    AND type = 4 
            SELECT  @dTotal = @dTotal + @dQty
            SELECT  @dQty = ISNULL(SUM(tax_total), 0)
            FROM    DlyData
            WHERE   btypeid = @szBtypeid AND RedOld = 'F'
                    AND vchtype = 52
            SELECT  @dTotal = ISNULL(@dTotal, 0) + ISNULL(@dQty, 0)
            SELECT  @dQty = ISNULL(@dTotal, 0)
          END
        ELSE 
          IF @szSelect = 'commission'  --委托发货
            BEGIN
              SELECT  @dQty = ISNULL(SUM(Tax_total), 0)
              FROM    DlyData
              WHERE   btypeid LIKE @szBtypeid + '%' AND RedOld = 'F'
                      AND vchtype IN (30, 25, 50)
                      AND pdetail = 2
                      AND [date] <= @EndDate  
				--结算
              SELECT  @dTotal = ISNULL(SUM(Tax_total), 0)
              FROM    DlyData
              WHERE   btypeid LIKE @szBtypeid + '%' AND RedOld = 'F'
                      AND vchtype = 26
                      AND [date] <= @enddate    
              SELECT  @dTotal = @dQty + @dTotal
				--期初
              SELECT  @dQty = ISNULL(SUM(total), 0)
              FROM    iniCommission
              WHERE   btypeid LIKE @szBtypeid + '%'
                      AND type = 1
              SELECT  @dTotal = ISNULL(@dQty, 0) + ISNULL(@dTotal, 0)
              SELECT  @dQty = ISNULL(@dTotal, 0)
            END
          ELSE 
            IF @szSelect = 'recommission' --受托结算
              BEGIN                
                SELECT  @dQty = ISNULL(SUM(Tax_total), 0)
                FROM    DlyData
                WHERE   btypeid LIKE @szBtypeid + '%' AND RedOld = 'F'
                        AND vchtype IN (31, 27, 51)
                        AND pdetail = 2
                        AND [date] <= @EndDate  

					--结算
                SELECT  @dTotal = ISNULL(SUM(Tax_total), 0)
                FROM    DlyData
                WHERE   btypeid LIKE @szBtypeid + '%' AND RedOld = 'F'
                        AND vchtype = 28
                        AND [date] <= @enddate    
                SELECT  @dTotal = @dQty + @dTotal
					--期初
                SELECT  @dQty = ISNULL(SUM(Taxtotal), 0)
                FROM    iniCommission
                WHERE   btypeid LIKE @szBtypeid + '%'
                        AND type = 5
                SELECT  @dTotal = ISNULL(@dQty, 0) + ISNULL(@dTotal, 0)
                SELECT  @dQty = ISNULL(@dTotal, 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].[FZGetStockInOut]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FZGetStockInOut]
GO


CREATE procedure FZGetStockInOut
(
	@PtypeId varchar(50),
	@BranchIdList varchar(8000),
	@KtypeIdList varchar(8000),
	@DateBegin varchar(15),
	@DateEnd varchar(15),
	@Mode Integer = 0,
	@ColorId Integer = -1,
	@SizeId Integer = -1,
	@attrib1 Integer = -1,
	@attrib2 Integer = -1,
	@attrib3 Integer = -1,
	@attrib4 Integer = -1,
	@attrib5 Integer = -1,
	@attrib6 Integer = -1,
	@attrib7 Integer = -1,
	@attrib8 Integer = -1,
	@attribTypeid1 Integer = -1,
	@attribTypeid2 Integer = -1,
	@attribTypeid3 Integer = -1,
	@attribTypeid4 Integer = -1,
	@attribTypeid5 Integer = -1,
	@attribTypeid6 Integer = -1,
	@attribTypeid7 Integer = -1,
	@attribTypeid8 Integer = -1,
	@ShowNoInOut Integer = -1,
	@OperatorId	VARCHAR(50)
)
as
	if @PtypeId = '00000' set @PtypeID = ''
	declare @PtypeIdLength integer
	set @PtypeIdLength = Len(@PtypeId) + 5
	if object_id('tempdb..#KtypeID') is not null drop table #KtypeID 
	create table #KtypeID  (KtypeId varchar(50), KID  [int] IDENTITY(1,1) )      
	Insert #KtypeID select KtypeId from FN_GetStockListOfBranch(@OperatorId,@BranchIdList,@KtypeIdList)
	if @Mode = 0 
	begin
		select Left(PtypeId ,@PtypeIdLength) as PtypeId ,KtypeId ,sum(QcQty) as QCQty, abs(sum(InQty)) As InQty, abs(sum(OutQty)) as OutQty, sum(QMQty) as QMQty from
		(select a.PtypeId,KtypeId,b.ColorId,b.SizeId, 0 as QCQty, b.Qty as InQty ,0 as OutQty ,0 as QMQty from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder where billtype IN (1,2,3,8) and b.Qty > 0 and date >= @DateBegin and Date <= @DateEnd  and Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) and RedOld = 'F'
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId,0 as QCQty,0 as InQty ,b.Qty as OutQty ,0 as QMQty from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder where billtype IN (1,2,3,8) and  b.Qty < 0 and date >= @DateBegin and Date <= @DateEnd and Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) and RedOld = 'F'
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, b.Qty as QCQty ,0 as InQty, 0 as OutQty, 0 as QMQty from inigoodsstocks a left join inigoodsdetail b on a.orderid = b.orderid where Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) 
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, b.Qty as QCQty, 0 as Inqty, 0 as OutQty, 0 as QMQty from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder where billtype IN (1,2,3,8) and Date < @DateBegin and Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) and RedOld = 'F'
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, 0 as QCQty, 0 as InQty, 0 as OutQty, b.Qty as QMQty from goodsstocks a left join goodsstockdetail b on a.orderid = b.orderid where Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) 
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, 0 as QCQty, 0 as Inqty, 0 as OutQty, -b.Qty as QMQty from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder where billtype IN (1,2,3,8) and Date > @DateEnd and Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) and RedOld = 'F'
		) a
		WHERE PtypeId IN (SELECT typeid FROM FN_GetPowerRangePList(@OperatorId,''))--操作员商品权限范围
		group by Left(PtypeId ,@PtypeIdLength), KtypeID		
		order by Left(PtypeId ,@PtypeIdLength),KtypeId
	end
	if @Mode = 1 
	begin
		select a.PtypeId ,KtypeId ,sum(QcQty) as QCQty, abs(sum(InQty)) As InQty, abs(sum(OutQty)) as OutQty, sum(QMQty) as QMQty, 
		right('00000'+cast(isnull(a.ColorId,-1) as varchar),5) as PCTypeid,right('00000'+cast(isnull(a.Sizeid,-1) as varchar),5) as PSTypeid ,
		(SELECT TOP 1 [Order] FROM [dbo].[Size] si WHERE si.SizeId = a.SizeID ) AS psOrder 
		from
		(select a.PtypeId,KtypeId,b.ColorId,b.SizeId, 0 as QCQty, b.Qty as InQty ,0 as OutQty ,0 as QMQty from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder where billtype IN (1,2,3,8) and b.Qty > 0 and date >= @DateBegin and Date <= @DateEnd  and Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) and RedOld = 'F'
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId,0 as QCQty,0 as InQty ,b.Qty as OutQty ,0 as QMQty from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder where billtype IN (1,2,3,8) and  b.Qty < 0 and date >= @DateBegin and Date <= @DateEnd and Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) and RedOld = 'F'
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, b.Qty as QCQty ,0 as InQty, 0 as OutQty, 0 as QMQty from inigoodsstocks a left join inigoodsdetail b on a.orderid = b.orderid where Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) 
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, b.Qty as QCQty, 0 as Inqty, 0 as OutQty, 0 as QMQty from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder where billtype IN (1,2,3,8) and Date < @DateBegin and Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) and RedOld = 'F'
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, 0 as QCQty, 0 as InQty, 0 as OutQty, b.Qty as QMQty from goodsstocks a left join goodsstockdetail b on a.orderid = b.orderid where Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) 
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, 0 as QCQty, 0 as Inqty, 0 as OutQty, -b.Qty as QMQty from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder where billtype IN (1,2,3,8) and Date > @DateEnd and Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) and RedOld = 'F'
  		) a 
                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b 
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid1) ls1
                  on  @attrib1 <> -1 and ls1.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b 
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid2) ls2
                  on  @attrib2 <> -1 and ls2.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid3) ls3
                  on  @attrib3 <> -1 and ls3.ptypeid = a.Ptypeid
                 
                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid4) ls4
                  on  @attrib4 <> -1 and ls4.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid5) ls5
                  on  @attrib5 <> -1 and ls5.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid6) ls6
                  on  @attrib6 <> -1 and ls6.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid7) ls7
                  on  @attrib7 <> -1 and ls7.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid8) ls8
                  on  @attrib8 <> -1 and ls8.ptypeid = a.Ptypeid
                      Where
				Colorid = case @ColorId when -1 then ColorId else @ColorId end and
				SizeId = case @SizeId when -1 then SizeId else @SizeId end and
        isnull(ls1.attributeid,-1) =  case when @attrib1 = -1 then isnull(ls1.attributeid,-1) else @attrib1 end
        and isnull(ls2.attributeid,-1) =  case when @attrib2 = -1 then isnull(ls2.attributeid,-1) else @attrib2 end
        and isnull(ls3.attributeid,-1) =  case when @attrib3 = -1 then isnull(ls3.attributeid,-1) else @attrib3 end
        and isnull(ls4.attributeid,-1) =  case when @attrib4 = -1 then isnull(ls4.attributeid,-1) else @attrib4 end
        and isnull(ls5.attributeid,-1) =  case when @attrib5 = -1 then isnull(ls5.attributeid,-1) else @attrib5 end
        and isnull(ls6.attributeid,-1) =  case when @attrib6 = -1 then isnull(ls6.attributeid,-1) else @attrib6 end
        and isnull(ls7.attributeid,-1) =  case when @attrib7 = -1 then isnull(ls7.attributeid,-1) else @attrib7 end
        and isnull(ls8.attributeid,-1) =  case when @attrib8 = -1 then isnull(ls8.attributeid,-1) else @attrib8 end
	and a.PtypeId IN (SELECT typeid FROM FN_GetPowerRangePList(@OperatorId,''))--操作员商品权限范围
				group by a.PtypeId, KtypeID,a.ColorId,a.SizeId 
				having case @ShowNoInOut when 1 then 1 else abs(sum(InQty)) end> 0 or case @ShowNoInOut when 1 then 1 else abs(sum(OutQty)) end> 0	
				order by a.PtypeId,a.colorId,psOrder,a.sizeId,KtypeId
	end	 
	if @Mode = 2 
	begin
		select a.PtypeId ,KtypeId ,sum(QcQty) as QCQty, abs(sum(InQty)) As InQty, abs(sum(OutQty)) as OutQty, sum(QMQty) as QMQty from
		(select a.PtypeId,KtypeId,b.ColorId,b.SizeId, 0 as QCQty, b.Qty as InQty ,0 as OutQty ,0 as QMQty from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder where billtype IN (1,2,3,8) and b.Qty > 0 and date >= @DateBegin and Date <= @DateEnd  and Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) and RedOld = 'F'
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId,0 as QCQty,0 as InQty ,b.Qty as OutQty ,0 as QMQty from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder where billtype IN (1,2,3,8) and  b.Qty < 0 and date >= @DateBegin and Date <= @DateEnd and Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) and RedOld = 'F'
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, b.Qty as QCQty ,0 as InQty, 0 as OutQty, 0 as QMQty from inigoodsstocks a left join inigoodsdetail b on a.orderid = b.orderid where Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) 
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, b.Qty as QCQty, 0 as Inqty, 0 as OutQty, 0 as QMQty from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder where billtype IN (1,2,3,8) and Date < @DateBegin and Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) and RedOld = 'F'
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, 0 as QCQty, 0 as InQty, 0 as OutQty, b.Qty as QMQty from goodsstocks a left join goodsstockdetail b on a.orderid = b.orderid where Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) 
		union all
		select a.PtypeId,KtypeId,b.ColorId,b.SizeId, 0 as QCQty, 0 as Inqty, 0 as OutQty, -b.Qty as QMQty from DlyData a left join Dlydatadetail b on a.dlyorder = b.dlyorder where billtype IN (1,2,3,8) and Date > @DateEnd and Left(PtypeId,Len(@PtypeID)) = @PtypeId and KtypeId in (select KtypeId from #KtypeID) and RedOld = 'F'
  		) a 
                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b 
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid1) ls1
                  on  @attrib1 <> -1 and ls1.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b 
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid2) ls2
                  on  @attrib2 <> -1 and ls2.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid3) ls3
                  on  @attrib3 <> -1 and ls3.ptypeid = a.Ptypeid
                 
                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid4) ls4
                  on  @attrib4 <> -1 and ls4.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid5) ls5
                  on  @attrib5 <> -1 and ls5.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid6) ls6
                  on  @attrib6 <> -1 and ls6.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid7) ls7
                  on  @attrib7 <> -1 and ls7.ptypeid = a.Ptypeid

                  left join (select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b
                                    where a.attributeid = b.attributeid and typeid = @attribTypeid8) ls8
                  on  @attrib8 <> -1 and ls8.ptypeid = a.Ptypeid
                      Where
        isnull(ls1.attributeid,-1) =  case when @attrib1 = -1 then isnull(ls1.attributeid,-1) else @attrib1 end
        and isnull(ls2.attributeid,-1) =  case when @attrib2 = -1 then isnull(ls2.attributeid,-1) else @attrib2 end
        and isnull(ls3.attributeid,-1) =  case when @attrib3 = -1 then isnull(ls3.attributeid,-1) else @attrib3 end
        and isnull(ls4.attributeid,-1) =  case when @attrib4 = -1 then isnull(ls4.attributeid,-1) else @attrib4 end
        and isnull(ls5.attributeid,-1) =  case when @attrib5 = -1 then isnull(ls5.attributeid,-1) else @attrib5 end
        and isnull(ls6.attributeid,-1) =  case when @attrib6 = -1 then isnull(ls6.attributeid,-1) else @attrib6 end
        and isnull(ls7.attributeid,-1) =  case when @attrib7 = -1 then isnull(ls7.attributeid,-1) else @attrib7 end
        and isnull(ls8.attributeid,-1) =  case when @attrib8 = -1 then isnull(ls8.attributeid,-1) else @attrib8 end
	and a.PtypeId IN (SELECT typeid FROM FN_GetPowerRangePList(@OperatorId,''))--操作员商品权限范围
				group by a.PtypeId,KtypeID 
				order by a.PtypeId,KtypeId
	end	 
  	drop table #KtypeID





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].[FZMXZBGetAllList]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZMXZBGetAllList]
GO


--  ********************************************************************************************
--  ||                                                                                        
--  ||   过程名称： F_MXZB_GetAllList                            
--  ||   过程功能：得到各个科目的明细（查询明细账本用）
--  ||=========================================================================================
--  ||   参数说明：  参数名称         类型                    意义                     输入输出
--  ||            -----------------------------------------------------------------------------
--  ||          得到各个科目的明细
--  || 		@cMode		varchar（5）
--  || 	                                        'A'	科目明细
--  || 	                                        'P'	商品明细
--  ||  	                                'B'	应收应付明细
--  ||  	                                'H'	换货单据明细
--  ||  	                                'S'	销售单据明细
--  ||  	                                'I'	进货单据明细
--  ||						'O'     退货单据明细
--  ||						'D'     加盟店配货订单明细
--  ||						'Q'     自营店配货订单明细
--  || 						'J'	加盟店零售明细
--  ||						'Shop'  商场专柜销售统计
--  || 						'Y'	销售优惠明细
--  || 						'YKCZKB'库存状况明细单据'
--  ||  	@szAtypeId	varchar(50),            会计科目编号
--  ||  	@szPtypeId	varchar(50),            商品编码
--  ||  	@szBtypeId	varchar(50),            往来单位编码
--  ||  	@szEtypeId	varchar(50),            职员编码
--  ||  	@szKtypeId	varchar(50),            仓库编码
--  ||  	@szPeriod	varchar(10),            会计期间
--  ||  	@szBeginData	varchar(10),            开始日期
--  ||  	@szEndData	varchar(10)             结束日期
--  ||  	@ifjs           varvhar(10)             0：统计未结算的，1：统计已经结算的，''：统计所有
--  ||=========================================================================================   
--  ||  返回值：  值                          说明
--  || --------------------------------------------------------------------------------------- 	 
--  ||  	 	返回 0		是成功
--  ||  	 	返回 -101	是没有数据
--  ||  	 	返回 -102	是查询失败
--  ||=========================================================================================   
 CREATE          PROCEDURE FZMXZBGetAllList
    (
      @cMode VARCHAR(30),
      @szAtypeId VARCHAR(50),
      @szPtypeId VARCHAR(50),
      @szBtypeId VARCHAR(50),
      @szEtypeId VARCHAR(50),
      @szKtypeId VARCHAR(2000),   --有仓库组控制，可能传入多个仓库ID的字符创
      @szPeriod VARCHAR(10),
      @szBeginData VARCHAR(10),
      @szEndData VARCHAR(10),
      @ifjs VARCHAR(1),
      @ifstop VARCHAR(1),
      @SaleTraitname VARCHAR(1000) = '',
      @deptid VARCHAR(50),
      @CustType VARCHAR(10) = '',
      @Branchid VARCHAR(2000) = '',
      @OperatorId VARCHAR(50),
      @IsStop BIT = 0,--是否包含停用商品 0：包含  1：不包含
      @IncludeYSYF VARCHAR(1) = 0 --是否包含预收预付
    )
 AS 
    SET nocount ON
    DECLARE @sql VARCHAR(8000)
    DECLARE @ROOT_ID VARCHAR(50)
    DECLARE @GOOD_ID VARCHAR(50)
    DECLARE @CASH_ID VARCHAR(50)
    DECLARE @CASH_BANK_ID VARCHAR(50)
    DECLARE @GETMONEYBILL INT
    DECLARE @SALEBILL INT
    DECLARE @SALEBACKBILL INT
    DECLARE @LENDSALEBILL INT 
    DECLARE @BUYBILL INT 
    DECLARE @BUYBACKBILL INT 
    DECLARE @BORROWBUYBILL INT 
    DECLARE @ALL_QTY NUMERIC(24, 10)
    DECLARE @ALL_TOTAL NUMERIC(24, 10)
    DECLARE @AP_ID VARCHAR(50)
    DECLARE @AR_ID VARCHAR(50)
    DECLARE @nPSonnum INT
    DECLARE @nBSonnum INT 
    DECLARE @nESonnum INT
    DECLARE @nKSonnum INT
    DECLARE @BORROW_KTYPE VARCHAR(10)
    DECLARE @LEND_KTYPE VARCHAR(10)
    DECLARE @where VARCHAR(100)  
    DECLARE @RECOMMISSION_PRICE_VCHTYPE INT
    DECLARE @COMMISSION_PRICE_VCHTYPE INT
    DECLARE @RECOMMISSION_JS_VCHTYPE INT
    DECLARE @COMMISSION_JS_VCHTYPE INT
    DECLARE @Pdetail INT
    DECLARE @RECOMMISSION_VCHTYPE INT
    DECLARE @COMMISSION_VCHTYPE INT
    DECLARE @RECOMMISSION_BACK_VCHTYPE INT
    DECLARE @COMMISSION_BACK_VCHTYPE INT
    SELECT  @Pdetail = 2
    SELECT  @RECOMMISSION_PRICE_VCHTYPE = 51--受托调价
    SELECT  @COMMISSION_PRICE_VCHTYPE = 50--委托调价
    SELECT  @RECOMMISSION_JS_VCHTYPE = 28--受托收货结算
    SELECT  @COMMISSION_JS_VCHTYPE = 26--委托结算
    SELECT  @RECOMMISSION_VCHTYPE = 27--受托收货
    SELECT  @COMMISSION_VCHTYPE = 25--委托代销
    SELECT  @RECOMMISSION_BACK_VCHTYPE = 31--受托收货退货
    SELECT  @COMMISSION_BACK_VCHTYPE = 30--委托退货单
    SELECT  @where = ''
    SELECT  @ROOT_ID = '00000'
    SELECT  @GOOD_ID = '0000100001'
    SELECT  @CASH_ID = '0000100003'
    SELECT  @CASH_BANK_ID = '0000100004'
    SELECT  @AR_ID = '0000100005'
    SELECT  @AP_ID = '0000200001'
    SELECT  @GETMONEYBILL = 4
    SELECT  @SALEBILL = 11
    SELECT  @SALEBACKBILL = 45
    SELECT  @LENDSALEBILL = 89
    SELECT  @BUYBILL = 34
    SELECT  @BUYBACKBILL = 6
    SELECT  @BORROWBUYBILL = 73
    SELECT  @nPSonnum = [sonnum]
    FROM    Ptype
    WHERE   [typeid] = @szPtypeId
    SELECT  @nBSonnum = [sonnum]
    FROM    btype
    WHERE   [typeid] = @szBtypeId
    SELECT  @nESonnum = [sonnum]
    FROM    employee
    WHERE   [typeid] = @szEtypeId
    SELECT  @nKSonnum = [sonnum]
    FROM    stock
    WHERE   [typeid] = @szKtypeId
    IF @nPSonnum = NULL 
        SELECT  @nPSonnum = 0
    IF @nBSonnum = NULL 
        SELECT  @nBSonnum = 0
    IF @nESonnum = NULL 
        SELECT  @nESonnum = 0
    IF @nKSonnum = NULL 
        SELECT  @nKSonnum = 0
    SELECT  @BORROW_KTYPE = '9999999998'
    SELECT  @LEND_KTYPE = '9999999999'
    DECLARE @Business_EXPENSE_ID VARCHAR(50)   
    SELECT  @Business_EXPENSE_ID = '0000400003' 
	
	--新增存储过程 GetDig，用来取小数配置。以后所有报表存储过程对小数位的取舍用以下方式。
    DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
    EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
	
    IF @SaleTraitname = '' 
        SET @SaleTraitname = '全部'
    IF @ifjs <> '' 
        SELECT  @where = @where + '  and ifjs = (case ' + @ifjs
                + ' when 0 then ifjs else ' + @ifjs + ' end) ' 	
    IF ( @szAtypeId = '' )
        OR ( @szAtypeId = @ROOT_ID ) 
        SELECT  @szAtypeId = '%%'
    IF ( @szPtypeId = '' )
        OR ( @szPtypeId = @ROOT_ID ) 
        SELECT  @szPtypeId = '%%'
    IF ( @szBtypeId = '' )
        OR ( @szBtypeId = @ROOT_ID ) 
        SELECT  @szBtypeId = '%%'
    IF @deptid = NULL 
        SELECT  @deptid = ''
	--if @cMode in( 'G','B','E','BK1')		
	--begin
    IF ( @szEtypeId = '' ) 
        SELECT  @szEtypeId = '%%' --职员费用明细帐，为空时是所有职员
	--end
	--else
	--begin
		--if (@szEtypeId='')  Select @szEtypeId='%%' -- 其他情况为空或者为‘00000’是所有职员
	--end
    IF @ifstop = '' 
        SELECT  @ifstop = 1
    IF ( @szKtypeId = '' )
        OR ( @szKtypeId = @ROOT_ID ) 
        SELECT  @szKtypeId = '%%'
	--if not exists(Select * From Dlyndx Where [date]>=@szBeginData and [date]<=@szEndData) and upper(@cMode)<>'A'  goto error2
	
    IF @cMode = 'A' 
        GOTO GetAtype
    ELSE 
        IF @cMode = 'P' 
            GOTO GetPtype--库存商品明细
        ELSE 
            IF @cMode IN ( 'B', 'BK', 'BK1', 'QueryConBtype', 'QueryBtypeSale' ) 
                GOTO GetBtype --往来单明细
            ELSE 
                IF @cMode = 'E' 
                    GOTO GetEtype --职员明细
                ELSE 
                    IF @cMode = 'I' 
                        GOTO GetBuy --进货明细(包括受托结算)
                    ELSE 
                        IF @cMode = 'IG' GOTO GetBuy1--进货明细(只包含进货和退货)
                        ELSE 
                            IF @cMode = 'S' 
                                GOTO GetSale --销售明细
                            ELSE 
                                IF @cMode = 'J' 
                                    GOTO GetJoinSale --加盟店销售明细
                                ELSE 
                                    IF @cMode = 'D' 
                                        GOTO GetJoinorder --加盟店订单明细
                                    ELSE 
                                        IF @cMode = 'Q' 
                                            GOTO GetBuyorder --自营店订单明细
                                        ELSE 
                                            IF @cMode = 'O' 
                                                GOTO GetBuyback --进货退货明细
                                            ELSE 
                                                IF @cMode = 'H' 
                                                    GOTO GetSaleExchange--销售换货明细
                                                ELSE 
                                                    IF @cMode = 'Y' 
                                                        GOTO GetSalepreferential --优惠统计明细
                                                    ELSE 
                                                        IF @cMode = 'G' 
                                                            GOTO GetExp  --8。
                                                        ELSE 
                                                            IF @cMode = 'JS' GOTO GetJoinStock --加盟店库存明细
                                                            ELSE 
                                                                IF @cMode = 'BO' GOTO GetBuyandback--进货退货分析明细
                                                                ELSE 
                                                                    IF UPPER(@cMode) = 'SELF' 
                                                                        GOTO GetSelf --自营店库存明细
                                                                    ELSE 
                                                                        IF UPPER(@cMode) = 'SHOP' 
                                                                            GOTO GetShop --商场专柜明细
                                                                        ELSE 
                                                                            IF UPPER(@cMode) = 'JOIN' 
                                                                                GOTO GetJoin --加盟店销售统计明细
                                                                            ELSE 
                                                                                IF UPPER(@cMode) = 'TEMP' GOTO GetTemp --取得周转仓库的明细账本
                                                                                ELSE 
                                                                                    IF UPPER(@cMode) = 'LSTJFX' 
                                                                                        GOTO GetRetailSale--零售销售统计
                                                                                    ELSE 
                                                                                        IF UPPER(@cMode) = 'KHXSFX' 
                                                                                            GOTO GetBtypeSaleAnalyse--客户销售分析
                                                                                        ELSE 
                                                                                            IF UPPER(@cMode) = 'YKCZKB' 
                                                                                                GOTO GetStockBillDetail --库存状况单据明细
                                                                                            ELSE 
                                                                                                IF UPPER(@cMode) = 'YKCZKB_JOIN' 
                                                                                                    GOTO GetStockJOINBillDetail 
                                                                                                ELSE 
                                                                                                    IF UPPER(@cMode) = 'SCDZTJ' 
                                                                                                        GOTO getSCDZTJ --商场对账统计

--取得周转仓库的明细账本
    getSCDZTJ:

    SELECT  a.VchCode,
            a.[Date],
            a.Number,
            a.summary,
            a.vchtype,
            a.Redold,
            a.btypeid,
            a.redword,
            ( ISNULL(( SELECT   SUM(CASE atypeid
                                      WHEN '0000200001' THEN -total
                                      ELSE total
                                    END)
                       FROM     dlya
                       WHERE    ( atypeid = '0000200001'
                                  OR atypeid = '0000100005'
                                )
                                AND VchCode = a.VchCode
                     ), 0) ) AS YSHKMoney,
            ( CASE WHEN a.VchType IN ( 36 ) THEN SUM(a.total)
                   ELSE 0
              END ) FyMoney,
            ( CASE WHEN a.vchtype IN ( 4, 66 ) THEN SUM(b.total)
                   ELSE SUM(c.total)
              END ) AS HKMoney,
            ( SELECT    SUM(-SaleMoney)
              FROM      dlydata
              WHERE     vchcode = a.vchcode
                        AND billtype = 2
                        AND usedtype = CASE WHEN vchtype IN ( 222, 224 )
                                            THEN 1
                                            ELSE usedtype
                                       END
            ) AS Total,
            ( SELECT    ROUND(-MarketDiscount1 *CONVERT(NUMERIC(24,10),SUM(SaleMoney)) / 100, @dig_total)
              FROM      dlydata
              WHERE     vchcode = a.vchcode
                        AND billtype = 2
                        AND usedtype = CASE WHEN vchtype IN ( 222, 224 )
                                            THEN 1
                                            ELSE usedtype
                                       END
             GROUP BY MarketDiscount1                         
            ) AS DeductTotal
    FROM    dlyndx a
            LEFT JOIN ( SELECT  VchCode,
                                total
                        FROM    dlya
                        WHERE   vchCode IN ( SELECT vchCode
                                             FROM   dlyndx
                                             WHERE  vchtype IN ( 4, 66 ) )
                                AND usedtype = 1
                                AND Btypeid LIKE @szBtypeId + '%'
                                AND LEFT(btypeid, 5) = '00003'
                      ) b ON b.vchCode = a.VchCode
            LEFT JOIN ( SELECT  VchCode,
                                Total,
                                atypeid
                        FROM    DlyA
                        WHERE   Btypeid LIKE @szBtypeId + '%'
                      ) c ON c.VchCode = a.VchCode
                             AND c.Atypeid = a.Atypeid
    WHERE   a.vchType IN ( 4, 66, 36, 250, 100, 101 )
            AND ( ( a.Btypeid LIKE @szBtypeId + '%' )
                  OR a.vchcode IN ( SELECT  vchCode
                                    FROM    dlya
                                    WHERE   btypeid LIKE @szBtypeId + '%'
                                            AND vchtype = 125
                                            AND ( atypeid = '0000200001'
                                                  OR atypeid = '0000100005'
                                                ) )
                )
            AND a.[Date] >= @szBeginData
            AND a.[Date] <= @szEndData
            AND a.draft = '2'
            AND LEFT(btypeid, 5) = '00003'
    GROUP BY a.VchCode,
            a.btypeid,
            a.[Date],
            a.Number,
            a.VchType,
            a.summary,
            a.vchtype,
            a.Atypeid,
            a.redword,
            a.Redold,
            a.total
    ORDER BY a.[date],
            a.Number,
            a.vchtype DESC
    GOTO Succee

    GetTemp:
    SELECT  dn.date,
            dn.vchtype,
            number,
            dn.summary AS Comment,
            CASE WHEN d.qty <= 0 THEN ABS(ISNULL(d.qty, 0))
                 ELSE 0
            END AS Qtyin,
            CASE WHEN d.qty > 0 THEN ABS(ISNULL(d.qty, 0))
                 ELSE 0
            END AS Qtyout,
            ISNULL(d.qty, 0) AS qty,
            fullname AS pfullname,
            usercode AS pusercode,
            ptypeid,
            usercode,
            ISNULL(d.costTotal, 0) AS total,
            dn.vchcode,
            p.fullname,
            dn.redold,
            d.redword
    FROM    dlydata d,
            dlyndx dn,
            FN_GetPowerRangePList(@OperatorId, '') p
    WHERE   dn.vchcode = d.vchcode
            AND dn.vchtype IN ( 212, 215, 240, 218 )
            AND d.ktypeid = '99999'
            AND dn.date >= @szBeginData
            AND dn.date <= @szEndData
            AND d.ptypeid = p.typeid
            AND p.typeid LIKE @szPtypeId
    UNION ALL
    SELECT  dn.date,
            dn.vchtype,
            number,
            dn.summary AS Comment,
            CASE WHEN d.qty <= 0 THEN ABS(ISNULL(d.qty, 0))
                 ELSE 0
            END AS Qtyin,
            CASE WHEN d.qty > 0 THEN ABS(ISNULL(d.qty, 0))
                 ELSE 0
            END AS Qtyout,
            ISNULL(d.qty, 0) AS qty,
            fullname AS pfullname,
            usercode AS pusercode,
            ptypeid,
            usercode,
            ROUND(ISNULL(d.qty * d.costprice, 0),@dig_total) AS total,
            dn.vchcode,
            p.fullname,
            dn.redold,
            d.redword
    FROM    dlydata d,
            dlyndx dn,
            FN_GetPowerRangePList(@OperatorId, '') p
    WHERE   dn.vchcode = d.vchcode
            AND dn.vchtype = 230
            AND d.Ktypeid = '99999'
            AND dn.date >= @szBeginData
            AND dn.date <= @szEndData
            AND d.ptypeid = p.typeid
            AND p.typeid LIKE @szPtypeId
    ORDER BY dn.vchcode
    GOTO succee
	
--	得到会计科目的明细
    GetAtype:
	
    SELECT  a.[fullname],
            da.[vchcode],
            da.[vchtype],
            ISNULL(da.[total], 0) AS Total,
            CASE WHEN da.total > 0 THEN ISNULL(da.total, 0)
                 ELSE 0
            END AS Increase,
            CASE WHEN da.total < 0 THEN ABS(ISNULL(da.total, 0))
                 ELSE 0
            END AS Reduce,
            da.[date],
            ISNULL(dn.[number], '') AS number,
            ISNULL(dn.[summary], '') AS comment,
            dn.redold,
            da.redword
    FROM    ( SELECT    *
              FROM      atype
              WHERE     [deleted] <> 1
            ) a,
            ( SELECT    *
              FROM      DlyA
              WHERE     @szBeginData <= [date]
                        AND @szEndData >= [date]
            ) da,
            ( SELECT    *
              FROM      DlyNdx
              WHERE     @szBeginData <= [date]
                        AND @szEndData >= [date]
       --                 and 
       --                 (
							--(@szAtypeId='0000100001' AND ((@Branchid='00001' and VchType not IN(212,218)) or (@Branchid<>'00001' )))
							--OR @szAtypeId<>'0000100001'
       --                 )
            ) dn
    WHERE   LEFT(da.[atypeId], LEN(@szAtypeId)) LIKE @szAtypeId
            AND da.[vchcode] = dn.[vchcode]
            AND a.[typeid] = da.[atypeid]
            AND a.BranchID = da.BranchId
           -- AND a.BranchID LIKE @Branchid + '%'
            AND EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangeBCList(@OperatorId, @Branchid) b
                         WHERE  a.branchid = b.branchid )
    UNION ALL
    SELECT  a.[fullname],
            da.[vchcode],
            da.[vchtype],
            ISNULL(da.[total], 0) AS Total,
            CASE WHEN da.total > 0 THEN ISNULL(da.total, 0)
                 ELSE 0
            END AS Increase,
            CASE WHEN da.total < 0 THEN ABS(ISNULL(da.total, 0))
                 ELSE 0
            END AS Reduce,
            da.[date],
            '' AS number,
            '会员卡存储金额' AS comment,
            'F' AS redold,
            da.redword
    FROM    ( SELECT    *
              FROM      atype
              WHERE     [deleted] <> 1
            ) a,
            ( SELECT    *
              FROM      DlyA
              WHERE     @szBeginData <= [date]
                        AND @szEndData >= [date]
            ) da
    WHERE   LEFT(da.[atypeId], LEN(@szAtypeId)) LIKE @szAtypeId
            AND a.[typeid] = da.[atypeid]
            AND da.vchcode = 0
            AND a.BranchID = da.BranchId
          --  AND a.BranchID LIKE @Branchid + '%'
            AND EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangeBCList(@OperatorId, @Branchid) b
                         WHERE  a.branchid = b.branchid )
    ORDER BY da.vchcode
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	--Order by da.[vchcode]
--	得到往来客户的明细

    GetBtype:
--	得到应收应付的明细
    IF @cMode = 'QueryBtypeSale' 
        BEGIN
            SELECT  v.*,
                    atypeid
            FROM    ( SELECT    a.vchcode,
                                a.vchtype,
                                a.atypeid,
                                a.date,
                                b.redold,
                                a.btypeid,
                                b.number,
                                b.summary AS comment,
                                a.total,
                                CASE WHEN a.total > 0 THEN a.total
                                     ELSE 0
                                END AS increase,
                                CASE WHEN a.total < 0 THEN -1 * a.total
                                     ELSE 0
                                END AS reduce,
                                -( a.Total ) AS ReverseTotal,
                                a.redword,
                                b.BranchId
                      FROM      dlyndx b
                                INNER JOIN dlya a ON b.vchcode = a.vchcode
                                LEFT JOIN btype c ON a.btypeid = c.typeid
                      WHERE     @szBeginData <= b.[date]
                                AND @szEndData >= b.[date]
                                AND a.atypeid = @AR_ID
                                AND b.vchtype IN ( 100, 101, 11, 45, 26, 24,
                                                   13, 12, 222, 224, 4, 36, 93,
                                                   115, 66 )
                                AND a.btypeid LIKE @szbtypeid + '%'
                      UNION ALL
                      SELECT    a.vchcode,
                                a.vchtype,
                                a.atypeid,
                                a.date,
                                b.redold,
                                a.btypeid,
                                b.number,
                                b.summary AS comment,
                                -1 * a.total total,
                                CASE WHEN a.total < 0 THEN -1 * a.total
                                     ELSE 0
                                END AS increase,
                                CASE WHEN a.total > 0 THEN a.total
                                     ELSE 0
                                END AS reduce,
                                a.total AS ReverseTotal,
                                a.redword,
                                b.BranchId
                      FROM      dlyndx b
                                INNER JOIN dlya a ON b.vchcode = a.vchcode
                                LEFT JOIN btype c ON a.btypeid = c.typeid
                      WHERE     @szBeginData <= b.[date]
                                AND @szEndData >= b.[date]
                                AND b.vchtype IN ( 100, 101, 11, 45, 26, 24,
                                                   13, 12, 222, 224, 4, 36, 93,
                                                   115, 66 )
                                AND a.atypeid = @AP_ID
                                AND a.btypeid LIKE @szbtypeid + '%'
                      UNION ALL
                      SELECT DISTINCT
                                a.vchcode,
                                a.vchtype,
                                '' AS atypeid,
                                a.date,
                                b.redold,
                                a.btypeid,
                                b.number,
                                b.summary AS comment,
                                0 AS total,
                                0 AS increase,
                                0 AS reduce,
                                0 AS ReverseTotal,
                                a.redword,
                                b.BranchId
                      FROM      dlyndx b
                                INNER JOIN ( SELECT DISTINCT
                                                    btypeid,
                                                    vchcode,
                                                    vchtype,
                                                    [date],
                                                    redword
                                             FROM   dlya
                                             WHERE  vchcode NOT IN (
                                                    SELECT  vchcode
                                                    FROM    dlya
                                                    WHERE   atypeid = '0000100005'
                                                            OR atypeid = '0000200001' )
                                           ) a ON b.vchcode = a.vchcode
                                LEFT JOIN btype c ON a.btypeid = c.typeid
                      WHERE     @szBeginData <= b.[date]
                                AND @szEndData >= b.[date]
                                AND b.vchtype IN ( 100, 101, 11, 45, 26, 24,
                                                   13, 12, 222, 224, 4, 36, 93,
                                                   115, 66 )
                                AND a.btypeid LIKE @szbtypeid + '%'
                    ) v
                    LEFT JOIN atype aa ON v.atypeid = aa.typeid
                                          AND v.BranchId = aa.BranchId
            WHERE  -- v.BranchID LIKE @Branchid + '%'  AND 
					EXISTS ( SELECT 1
                                 FROM   FN_GetPowerRangeBCList(@OperatorID, @Branchid)
                                 WHERE  BranchID = v.branchid )
            ORDER BY v.vchcode	
            IF @@rowcount = 0 
                GOTO error2
            GOTO succee

        END
    IF ( @szAtypeId = @AR_ID )
        OR ( @szAtypeId = @AP_ID ) 
        BEGIN
            IF @cMode = 'BK' 
                SELECT  @szEtypeId = '%%'
            IF @cMode <> 'QueryConBtype' 
                BEGIN
                    SELECT  v.*,
                            aa.fullname AS afullname
                    FROM    ( SELECT    a.vchcode,
                                        a.vchtype,
                                        a.atypeid,
                                        a.date,
                                        a.branchid,
                                        b.redold,
                                        c.fullname AS bfullname,
                                        b.number,
                                        b.summary AS comment,
                                        a.total,
                                        CASE WHEN a.total > 0 THEN a.total
                                             ELSE 0
                                        END AS increase,
                                        CASE WHEN a.total < 0
                                             THEN -1 * a.total
                                             ELSE 0
                                        END AS reduce,
                                        -( a.Total ) AS ReverseTotal,
                                        a.redword
                              FROM      dlyndx b
                                        INNER JOIN dlya a ON b.vchcode = a.vchcode
                                        LEFT JOIN btype c ON a.btypeid = c.typeid
                              WHERE     @szBeginData <= b.[date]
                                        AND @szEndData >= b.[date]
                                        AND a.atypeid = @AR_ID                                       
                                        AND a.btypeid LIKE @szbtypeid + '%'
                                        AND b.etypeid LIKE @szetypeid + '%'
                              UNION ALL
                              SELECT    a.vchcode,
                                        a.vchtype,
                                        a.atypeid,
                                        a.date,
                                        a.branchid,
                                        b.redold,
                                        c.fullname AS bfullname,
                                        b.number,
                                        b.summary AS comment,
                                        -1 * a.total total,
                                        CASE WHEN a.total < 0
                                             THEN -1 * a.total
                                             ELSE 0
                                        END AS increase,
                                        CASE WHEN a.total > 0 THEN a.total
                                             ELSE 0
                                        END AS reduce,
                                        a.total AS ReverseTotal,
                                        a.redword
                              FROM      dlyndx b
                                        INNER JOIN dlya a ON b.vchcode = a.vchcode
                                        LEFT JOIN btype c ON a.btypeid = c.typeid
                              WHERE     @szBeginData <= b.[date]
                                        AND @szEndData >= b.[date]
                                        AND a.atypeid = @AP_ID
                                        AND a.btypeid LIKE @szbtypeid + '%'
                                        AND b.etypeid LIKE @szetypeid + '%'
                                        UNION ALL  --预收
                              SELECT    a.vchcode,
                                        a.vchtype,
                                        a.atypeid,
                                        a.date,
                                        a.branchid,
                                        b.redold,
                                        c.fullname AS bfullname,
                                        b.number,
                                        b.summary AS comment,
                                        -1 * a.total total,
                                        CASE WHEN a.total < 0
                                             THEN -1 * a.total
                                             ELSE 0
                                        END AS increase,
                                        CASE WHEN a.total > 0 THEN a.total
                                             ELSE 0
                                        END AS reduce,
                                        a.total AS ReverseTotal,
                                        a.redword
                              FROM      dlyndx b
                                        INNER JOIN dlya a ON b.vchcode = a.vchcode
                                        LEFT JOIN btype c ON a.btypeid = c.typeid
                              WHERE     @szBeginData <= b.[date]
                                        AND @szEndData >= b.[date]
                                        AND a.atypeid IN ('0000200888')                                        
                                        AND @IncludeYSYF = '1'
                                        AND @szAtypeId = @AR_ID
                                        AND a.btypeid LIKE @szbtypeid + '%'
                                        AND b.etypeid LIKE @szetypeid + '%'       
                                        UNION ALL  --预付
                              SELECT    a.vchcode,
                                        a.vchtype,
                                        a.atypeid,
                                        a.date,
                                        a.branchid,
                                        b.redold,
                                        c.fullname AS bfullname,
                                        b.number,
                                        b.summary AS comment,
                                        -1 * a.total total,                                        
                                        CASE WHEN a.total > 0 THEN a.total
                                             ELSE 0
                                        END AS increase,
                                             CASE WHEN a.total < 0 --注意此处的写法，程序里面把这两个字段是调整了的，这里也要相应调整一下
                                             THEN -1*a.total
                                             ELSE 0
                                        END AS reduce,
                                        
                                        a.total AS ReverseTotal,
                                        a.redword
                              FROM      dlyndx b
                                        INNER JOIN dlya a ON b.vchcode = a.vchcode
                                        LEFT JOIN btype c ON a.btypeid = c.typeid
                              WHERE     @szBeginData <= b.[date]
                                        AND @szEndData >= b.[date]
                                        AND a.atypeid IN ('0000100888')                                        
                                        AND @IncludeYSYF = '1'
                                        AND @szAtypeId = @AP_ID
                                        AND a.btypeid LIKE @szbtypeid + '%'
                                        AND b.etypeid LIKE @szetypeid + '%'                                    
                                        
                            ) v --select * from dlya where vchcode = 13
                            LEFT JOIN atype aa ON v.atypeid = aa.typeid
                                                  AND v.branchid = aa.branchid
                    WHERE   --v.branchid LIKE @Branchid + '%' AND
                             EXISTS ( SELECT 1
                                         FROM   FN_GetPowerRangeBCList(@OperatorID, @Branchid)
                                         WHERE  BranchID = v.branchid )
                    ORDER BY v.vchcode
                END
            ELSE 
                BEGIN
                    SELECT  v.*,
                            atypeid
                    FROM    ( SELECT    a.vchcode,
                                        a.vchtype,
                                        a.atypeid,
                                        a.date,
                                        b.redold,
                                        a.btypeid,
                                        b.number,
                                        b.summary AS comment,
                                        a.total,
                                        CASE WHEN a.total > 0 THEN a.total
                                             ELSE 0
                                        END AS increase,
                                        CASE WHEN a.total < 0
                                             THEN -1 * a.total
                                             ELSE 0
                                        END AS reduce,
                                        -( a.Total ) AS ReverseTotal,
                                        a.redword,
                                        b.BranchId
                              FROM      dlyndx b
                                        INNER JOIN dlya a ON b.vchcode = a.vchcode
                                        LEFT JOIN btype c ON a.btypeid = c.typeid
                              WHERE     @szBeginData <= b.[date]
                                        AND @szEndData >= b.[date]
                                        AND a.atypeid = @AR_ID
                                        AND b.vchtype IN ( 34, 6, 28, 11, 45,
                                                           12, 13, 100, 101,
                                                           222, 224, 24, 66, 4,
                                                           26 )
                                        AND a.btypeid LIKE @szbtypeid + '%'
                                        AND b.etypeid LIKE @szetypeid + '%'
                              UNION ALL
                              SELECT    a.vchcode,
                                        a.vchtype,
                                        a.atypeid,
                                        a.date,
                                        b.redold,
                                        a.btypeid,
                                        b.number,
                                        b.summary AS comment,
                                        -1 * a.total total,
                                        CASE WHEN a.total < 0
                                             THEN -1 * a.total
                                             ELSE 0
                                        END AS increase,
                                        CASE WHEN a.total > 0 THEN a.total
                                             ELSE 0
                                        END AS reduce,
                                        a.total AS ReverseTotal,
                                        a.redword,
                                        b.BranchId
                              FROM      dlyndx b
                                        INNER JOIN dlya a ON b.vchcode = a.vchcode
                                        LEFT JOIN btype c ON a.btypeid = c.typeid
                              WHERE     @szBeginData <= b.[date]
                                        AND @szEndData >= b.[date]
                                        AND a.atypeid = @AP_ID
                                        AND b.vchtype IN ( 34, 6, 28, 11, 45,
                                                           12, 13, 100, 101,
                                                           222, 224, 24, 66, 4,
                                                           26 )
                                        AND a.btypeid LIKE @szbtypeid + '%'
                                        AND b.etypeid LIKE @szetypeid + '%'
                              UNION ALL
                              SELECT DISTINCT
                                        a.vchcode,
                                        a.vchtype,
                                        '' AS atypeid,
                                        a.date,
                                        b.redold,
                                        a.btypeid,
                                        b.number,
                                        b.summary AS comment,
                                        0 AS total,
                                        0 AS increase,
                                        0 AS reduce,
                                        0 AS ReverseTotal,
                                        a.redword,
                                        b.BranchId
                              FROM      dlyndx b
                                        INNER JOIN ( SELECT DISTINCT
                                                            btypeid,
                                                            vchcode,
                                                            vchtype,
                                                            [date],
                                                            redword
                                                     FROM   dlya
                                                     WHERE  vchcode NOT IN (
                                                            SELECT  vchcode
                                                            FROM    dlya
                                                            WHERE   atypeid = '0000100005'
                                                                    OR atypeid = '0000200001' )
                                                   ) a ON b.vchcode = a.vchcode
                                        LEFT JOIN btype c ON a.btypeid = c.typeid
                              WHERE     @szBeginData <= b.[date]
                                        AND @szEndData >= b.[date]
                                        AND b.vchtype IN ( 34, 6, 28, 11, 45,
                                                           12, 13, 100, 101,
                                                           222, 224, 24, 66, 4,
                                                           26 )
                                        AND a.btypeid LIKE @szbtypeid + '%'
                                        AND b.etypeid LIKE @szetypeid + '%'
                            ) v
                            LEFT JOIN atype aa ON v.atypeid = aa.typeid
                                                  AND v.branchid = aa.branchid
                    WHERE   --v.BranchID LIKE @Branchid + '%' AND 
                            EXISTS ( SELECT 1
                                         FROM   FN_GetPowerRangeBCList(@OperatorID, @Branchid)
                                         WHERE  BranchID = v.branchid )
                END
        END
	--	得到往来单位的回款明细
	--	回款统计应为科目为现金、银行，单据为收款单，销售单，销售退货单三种单据
    ELSE 
        BEGIN
            IF @nESonnum > 0
                AND @szEtypeid <> '00000' 
                BEGIN
                    PRINT @szEtypeId
                    SELECT  da.[vchcode],
                            da.[vchtype],
                            da.[atypeid],
                            ISNULL(da.[total], 0) AS Total,
                            da.[date],
                            ISNULL(dn.[number], '') AS [number],
                            ISNULL(dn.[summary], '') AS comment,
                            da.etypeid,
                            da.atypeid,
                            v.typeid AS vtypeid,
                            dn.redold,
                            CASE WHEN da.total > 0 THEN ISNULL(da.total, 0)
                                 ELSE 0
                            END AS Increase,
                            CASE WHEN da.total < 0 THEN ISNULL(da.total, 0)
                                 ELSE 0
                            END AS Reduce,
                            -( da.Total ) AS ReverseTotal,
                            da.redword
                    FROM    ( SELECT    *
                              FROM      DlyA
                              WHERE     @szBeginData <= [Date]
                                        AND @szEndData >= [Date]
                                        AND ( ( LEFT([atypeid], LEN(@CASH_ID)) = @CASH_ID )
                                              OR ( LEFT([atypeid],
                                                        LEN(@CASH_BANK_ID)) = @CASH_BANK_ID )
                                            )
                                        AND [btypeid] LIKE @szBtypeId
                                        AND LEFT([etypeId], LEN(@szEtypeId)) LIKE @szEtypeId
                            ) da LEFT JOIN employee e on da.[etypeId]=e.[typeid],
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND [vchtype] IN ( @SALEBILL,
                                                           @SALEBACKBILL,
                                                           @GETMONEYBILL, 250,
                                                           222, 13, 12, 24,
                                                           100, 101, 26, 224 )
                            ) dn ,
                            atype a,
                            vchtype v
                    WHERE   da.[atypeid] = a.[typeid]
                            AND da.[vchcode] = dn.[vchcode]
                            AND da.[vchtype] = v.[vchtype]
                    ORDER BY da.[vchcode]
                END
            ELSE 
                BEGIN
			
                    SELECT  da.[vchcode],
                            da.[vchtype],
                            da.[atypeid],
                            ISNULL(da.[total], 0) AS Total,
                            da.[date],
                            ISNULL(dn.[number], '') AS [number],
                            ISNULL(dn.[summary], '') AS comment,
                            da.etypeid,
                            da.atypeid,
                            v.typeid AS vtypeid,
                            dn.redold,
                            CASE WHEN da.total > 0 THEN ISNULL(da.total, 0)
                                 ELSE 0
                            END AS Increase,
                            CASE WHEN da.total < 0 THEN ISNULL(da.total, 0)
                                 ELSE 0
                            END AS Reduce,
                            -( da.Total ) AS ReverseTotal,
                            da.redword
                    FROM    ( SELECT    *
                              FROM      DlyA
                              WHERE     @szBeginData <= [Date]
                                        AND @szEndData >= [Date]
                                        AND ( ( LEFT([atypeid], LEN(@CASH_ID)) = @CASH_ID )
                                              OR ( LEFT([atypeid],
                                                        LEN(@CASH_BANK_ID)) = @CASH_BANK_ID )
                                            )
                                        AND [btypeid] LIKE @szBtypeId
                                        AND [etypeId] LIKE @szEtypeId
                            ) da LEFT JOIN employee e on da.[etypeId]=e.[typeid] ,
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND [vchtype] IN ( @SALEBILL,
                                                           @SALEBACKBILL,
                                                           @GETMONEYBILL, 250,
                                                           222, 13, 12, 24,
                                                           100, 101, 26, 224 )
                            ) dn,
                            atype a,
                            vchtype v
                    WHERE   da.[atypeid] = a.[typeid]
                            AND da.[vchcode] = dn.[vchcode]
                            AND da.[vchtype] = v.[vchtype]
                    ORDER BY da.[vchcode]
                END
        END
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--	得到库存商品的明细
    GetPtype:
    IF @szKtypeID = '%%' 
        SET @szKtypeID = ''
    IF @szBTypeId = '%%' 
        SET @szBTypeId = ''
    IF OBJECT_ID('tempdb..#detail1') IS NOT NULL 
        DROP TABLE #detail1
    SELECT  vchcode,
            vchtype,
            SUM(Qty) AS Qty,
            SUM(Total) AS Total,
            date,
            number,
            comment,
            ptypeid,
            RedOld,
            redword,
            KtypeId,
            PSONKSON.UnitRate
    INTO    #detail1
    FROM    ( SELECT    a.[vchcode],
                        a.[vchtype],
                        ISNULL(a.[qty], 0) AS Qty,
                        ISNULL(a.[costtotal], 0) AS Total,
                        a.[date],
                        --dlyorder,
                        ISNULL(b.[number], '') AS [number],
                        ISNULL(b.[summary], '') AS comment,
                        ptypeid,
                        b.RedOld,
                        a.redword,
                        a.KtypeId,
                        C.UnitRate1 AS UnitRate
              FROM      ( SELECT    *
                          FROM      Dlydata
                          WHERE     @szBeginData <= [date]
                                    AND @szEndData >= [date]
                                    AND [pdetail] <> 2
                        ) a,
                        ( SELECT    *
                          FROM      DlyNdx
                          WHERE     @szBeginData <= [date]
                                    AND @szEndData >= [date]
                        ) b,
                        FN_GetPowerRangePList(@OperatorId, '') c
              WHERE     a.[ptypeId] LIKE @szPtypeId + '%'
                        AND EXISTS ( SELECT 1
                                     FROM   FN_GetStockListOfBranch(@OperatorID, @szBTypeId, @szKtypeID) bb
                                     WHERE  a.KtypeId = bb.KtypeId )
                        AND a.[vchcode] = b.[vchcode]
                        AND a.[ptypeid] = c.[typeid]
                        AND c.Stop IN ( CASE @IsStop
                                          WHEN 0 THEN c.stop
                                          ELSE 0
                                        END )--是否包含停用商品
              
            ) AS PSONKSON
    GROUP BY vchcode,
            vchtype,
            date,
            number,
            comment,
            ptypeid,
            RedOld,
            redword,
            KtypeId,
            --dlyorder,
            PSONKSON.UnitRate
    ORDER BY [vchcode]
	
    SELECT  vchcode,
            vchtype,
            qty,
            CASE WHEN Qty < 0 THEN ABS(qty)
                 ELSE 0
            END qtyout,
            CASE WHEN qty >= 0 THEN qty
                 ELSE 0
            END qtyin,
            Total,
            date,
            number,
            comment,
            ptypeid,
            RedOld,
            redword,
            unitrate
    FROM    #detail1
    ORDER BY [vchcode],
            [date],
            redold
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--	得到自营店库存商品的明细
    GetSelf:
    IF OBJECT_ID('tempdb..#detail1s') IS NOT NULL 
        DROP TABLE #detail1s
    SELECT  vchcode,
            vchtype,
            Qty,
            Total,
            date,
            number,
            comment,
            PtypeId,
            Pusercode,
            RedOld,
            redword
    INTO    #detail1s
    FROM    ( SELECT    a.[vchcode],
                        a.[vchtype],
                        ISNULL(a.[qty], 0) AS Qty,
                        ISNULL(a.[costtotal], 0) AS Total,
                        a.[date],
                        ISNULL(b.[number], '') AS [number],
                        ISNULL(b.[summary], '') AS comment,
                        c.[TypeId] AS PtypeId,
                        c.usercode AS Pusercode,
                        b.RedOld,
                        a.redword
              FROM      ( SELECT    *
                          FROM      dlydata
                          WHERE     @szBeginData <= [date]
                                    AND @szEndData >= [date]
                                    AND [pdetail] <> 2
                        ) a,
                        ( SELECT    *
                          FROM      DlyNdx
                          WHERE     @szBeginData <= [date]
                                    AND @szEndData >= [date]
                        ) b,
                        FN_GetPowerRangePList(@OperatorId, '') c
              WHERE     LEFT(a.[ptypeId], LEN(@szPtypeId)) LIKE @szPtypeId
                        AND LEFT(a.[ktypeId], LEN(@szKtypeId)) LIKE @szKtypeId
                        AND LEFT(a.ktypeid, 5) = '00007'
                        AND a.[vchcode] = b.[vchcode]
                        AND a.[ptypeid] = c.[typeid]
              UNION ALL
              SELECT    a.[vchcode],
                        a.[vchtype],
                        ISNULL(a.[qty], 0) AS Qty,
                        ISNULL(a.[costtotal], 0) AS Total,
                        a.[date],
                        ISNULL(b.[number], '') AS [number],
                        ISNULL(b.[summary], '') AS comment,
                        c.[TypeId] AS PtypeId,
                        c.usercode AS Pusercode,
                        b.RedOld,
                        a.redword
              FROM      ( SELECT    *
                          FROM      dlydata
                          WHERE     billtype = 3
                                    AND @szBeginData <= [date]
                                    AND @szEndData >= [date]
                                    AND ( [ktypeid] <> @BORROW_KTYPE
                                          AND [ktypeid] <> @LEND_KTYPE
                                          AND vchtype NOT IN ( '73', '89' )
                                          AND [pdetail] <> 2
                                        )
                        ) a,
                        ( SELECT    *
                          FROM      DlyNdx
                          WHERE     @szBeginData <= [date]
                                    AND @szEndData >= [date]
                        ) b,
                        FN_GetPowerRangePList(@OperatorId, '') c
              WHERE     a.[atypeId] = @GOOD_ID
                        AND LEFT(a.[ptypeId], LEN(@szPtypeId)) LIKE @szPtypeId
                        AND LEFT(a.[ktypeId], LEN(@szKtypeId)) LIKE @szKtypeId
                        AND LEFT(a.ktypeid, 5) = '00007'
                        AND a.[vchcode] = b.[vchcode]
                        AND a.[ptypeid] = c.[typeid]
            ) AS PSONKSON
    ORDER BY [vchcode]
	
    SELECT  vchcode,
            vchtype,
            qty,
            CASE WHEN Qty < 0 THEN ABS(qty)
                 ELSE 0
            END qtyout,
            CASE WHEN qty >= 0 THEN qty
                 ELSE 0
            END qtyin,
            Total,
            date,
            number,
            comment,
            PtypeId,
            Pusercode,
            RedOld,
            redword
    FROM    #detail1s
    ORDER BY vchcode
	
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--   得到库存状况表的单据明细
    GetStockBillDetail:
    BEGIN
        IF @szKtypeId = '%%' 
            SET @szKtypeId = ''
        IF @szBtypeId = '%%' 
            SET @szBtypeId = ''
        IF OBJECT_ID('tempdb..#detail1kczk') IS NOT NULL 
            DROP TABLE #detail1kczk
        SELECT  vchcode,
                vchtype,
                Qty,
                Total,
                date,
                number,
                comment,
                PtypeId,
                Pusercode,
                RedOld,
                redword,
                dlyorder
        INTO    #detail1kczk
        FROM    ( SELECT    b.[vchcode],
                            b.[vchtype],
                            ISNULL(a.[qty], 0) AS Qty,
                            ISNULL(( a.[costtotal] ), 0) AS Total,
                            a.[date],
                            dlyorder,
                            ISNULL(b.[number], '') AS [number],
                            ISNULL(b.[summary], '') AS comment,
                            c.[typeId] AS PtypeId,
                            c.usercode AS Pusercode,
                            b.RedOld,
                            a.redword
                  FROM      ( SELECT    ptypeid,
                                        ktypeid,
                                        date,
                                        vchcode,
                                        vchtype,
                                        Qty,
                                        costtotal,
                                        redword,
                                        dlyorder
                              FROM      Dlydata
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND [PDETAIL] <> 2
                                        AND LEFT([ptypeId], LEN(@szPtypeId)) LIKE @szPtypeId
                                        + '%'
                                        AND EXISTS ( SELECT 1
                                                     FROM   FN_GetStockListOfBranch(@OperatorID, @szBTypeId, @szKtypeID) bb
                                                     WHERE  Dlydata.KtypeId = bb.KtypeId )
                            ) a,
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                            ) b,
                            FN_GetPowerRangePList(@OperatorId, '') c
                  WHERE     a.[ptypeId] LIKE @szPtypeId + '%'
                            AND a.[vchcode] = b.[vchcode]
                            AND a.[ptypeid] = c.[typeid]
                ) AS PSONKSON
        ORDER BY [vchcode]
	
	
        SELECT  [vchcode],
                [vchtype],
                SUM(qty),
                CASE WHEN SUM(qty) < 0 THEN SUM(ABS(qty))
                     ELSE 0
                END AS qtyout,
                CASE WHEN SUM(qty) >= 0 THEN SUM(qty)
                     ELSE 0
                END AS qtyin,
                SUM(Total),
                [date],
                [number],
                comment,
                PtypeId,
                Pusercode,
                RedOld,
                Redword
        FROM    #detail1kczk
        GROUP BY PtypeId,
                Pusercode,
                RedOld,
                Redword,
                [vchcode],
                [vchtype],
                [date],
                [number],
                comment,
                dlyorder
        ORDER BY vchcode
    END
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee

--加盟店库存明细单据单据具体类别：1 进货类，2销售类，3库存类，4加盟店销售类，5加盟店库存类,6财务类，7其他类
    GetStockJOINBillDetail:
    IF @szKtypeId = '%%' 
        SET @szKtypeId = ''
    IF @szBtypeId = '%%' 
        SET @szBtypeId = ''
    IF OBJECT_ID('tempdb..#detail1kczkJoin') IS NOT NULL 
        DROP TABLE #detail1kczkJoin
    SELECT  vchcode,
            vchtype,
            Qty,
            Total,
            date,
            number,
            comment,
            ptypeid,
            RedOld,
            redword
    INTO    #detail1kczkJoin
    FROM    ( SELECT    b.[vchcode],
                        b.[vchtype],
                        ISNULL(a.[qty], 0) AS Qty,
                        ISNULL(( a.[costtotal] ), 0) AS Total,
                        a.[date],
                        ISNULL(b.[number], '') AS [number],
                        ISNULL(b.[summary], '') AS comment,
                        ptypeid,
                        b.RedOld,
                        a.redword
              FROM      ( SELECT    ptypeid,
                                    ktypeid,
                                    date,
                                    vchcode,
                                    vchtype,
                                    Qty,
                                    costtotal,
                                    redword
                          FROM      Dlydata xx
                          WHERE     EXISTS ( SELECT 1
                                             FROM   FN_GetStockListOfBranch(@OperatorID, @szBTypeId, @szKtypeID) bb
                                             WHERE  xx.KtypeId = bb.KtypeId )
                                    AND ( billtype IN ( 4, 5 )
                                          OR ( billtype = 2
                                               AND vchtype IN ( 222, 224 )
                                               AND usedtype = CASE WHEN vchtype IN ( 222, 224 ) THEN ''
                                                                   ELSE usedtype
                                                              END
                                             )
                                        )
                                    AND @szBeginData <= [date]
                                    AND @szEndData >= [date]
                                    AND [PDETAIL] <> 2
                                    AND ptypeId LIKE @szPtypeId + '%'
		--and  ktypeId like @szKtypeId+'%'
                          
                        ) a,
                        ( SELECT    *
                          FROM      DlyNdx
                          WHERE     ( billtype IN ( 4, 5 )
                                      OR ( billtype = 2
                                           AND vchtype IN ( 222, 224 )
                                         )
                                    )
                                    AND @szBeginData <= [date]
                                    AND @szEndData >= [date]
                        ) b,
                        FN_GetPowerRangePList(@OperatorId, '') c
              WHERE     a.[ptypeId] LIKE @szPtypeId + '%'
                        AND a.[vchcode] = b.[vchcode]
                        AND a.[ptypeid] = c.[typeid]
            ) AS PSONKSON
    ORDER BY [vchcode]
	
	
    SELECT  [vchcode],
            [vchtype],
            qty,
            CASE WHEN qty < 0 THEN ABS(qty)
                 ELSE 0
            END AS qtyout,
            CASE WHEN qty >= 0 THEN qty
                 ELSE 0
            END AS qtyin,
            Total,
            [date],
            [number],
            comment,
            ptypeid,
            RedOld,
            redword
    FROM    #detail1kczkJoin
    ORDER BY vchcode
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee

---------得到加盟店的库存明细
    GetJoinStock:
    BEGIN
        IF @szBTypeId = '%'
            OR @szBTypeId = '%%' 
            SET @szBTypeId = ''
        IF @szKTypeId = '%'
            OR @szKTypeId = '%%' 
            SET @szKTypeId = ''
        IF ( LEN(@szBTypeId) >= 5 )
            AND ( @szKTypeId = '00004' )  --如果选择了加盟店机构则取消默认的仓库类
            SET @szKTypeId = ''
        IF OBJECT_ID('tempdb..#detail11') IS NOT NULL 
            DROP TABLE #detail11
        SELECT  vchcode,
                vchtype,
                Qty,
                Total,
                date,
                number,
                comment,
                ptypeid,
                RedOld,
                redword
        INTO    #detail11
        FROM    ( SELECT    a.[vchcode],
                            a.[vchtype],
                            ISNULL(a.[qty], 0) AS Qty,
                            ISNULL(( a.[costtotal] ), 0) AS Total,
                            a.[date],
                            ISNULL(b.[number], '') AS [number],
                            ISNULL(b.[summary], '') AS comment,
                            ptypeid,
                            b.RedOld,
                            a.redword
                  FROM      ( SELECT    *
                              FROM      dlydata
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND vchtype IN ( 226, 227 )
                            ) a,
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND vchtype IN ( 226, 227 )
                            ) b,
                            FN_GetPowerRangePList(@OperatorId, '') c
                  WHERE     LEFT(a.[ptypeId], LEN(@szPtypeId)) LIKE @szPtypeId
                            + '%'
                            AND EXISTS ( SELECT 1
                                         FROM   FN_GetStockListOfBranch(@OperatorID, @szBTypeId, @szKtypeID) bb
                                         WHERE  a.KtypeId = bb.KtypeId )
                            AND a.[vchcode] = b.[vchcode]
                            AND a.[ptypeid] = c.[typeid]
                  UNION ALL
                  SELECT    a.[vchcode],
                            a.[vchtype],
                            ISNULL(a.qty, 0) AS Qty,
                            ( CASE a.vchtype
                                WHEN 26 THEN ISNULL(( a.bargainTotal ), 0)
                                ELSE ISNULL(( a.costTotal ), 0)
                              END ) AS Total,
                            a.[date],
                            ISNULL(b.[number], '') AS [number],
                            ISNULL(b.[summary], '') AS comment,
                            ptypeid,
                            b.RedOld,
                            a.redword
                  FROM      ( SELECT    *
                              FROM      dlydata
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND ( vchtype IN ( 222, 224 )
                                              AND usedtype = CASE WHEN vchtype IN ( 222, 224 ) THEN ''
                                                                  ELSE '1'
                                                             END
                                            )
                            ) a,
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND ( vchtype IN ( 224, 222 ) )
                            ) b,
                            FN_GetPowerRangePList(@OperatorId, '') c
                  WHERE     LEFT(a.[ptypeId], LEN(@szPtypeId)) LIKE @szPtypeId
                            + '%'
                            AND EXISTS ( SELECT 1
                                         FROM   FN_GetStockListOfBranch(@OperatorID, @szBTypeId, @szKtypeID) bb
                                         WHERE  a.KtypeId = bb.KtypeId )
                            AND a.[vchcode] = b.[vchcode]
                            AND a.[ptypeid] = c.[typeid]
                  UNION ALL
                  SELECT    a.[vchcode],
                            a.[vchtype],
                            ISNULL(a.qty, 0) AS Qty,
                            ISNULL(( a.[costtotal] ), 0) AS Total,
                            a.[date],
                            ISNULL(b.[number], '') AS [number],
                            ISNULL(b.[summary], '') AS comment,
                            ptypeid,
                            b.RedOld,
                            a.redword
                  FROM      ( SELECT    *
                              FROM      dlydata
                              WHERE     usedtype = '1'
                                        AND @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND vchtype IN ( 140, 141, 142, 143,
                                                         144 )
                            ) a,
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND vchtype IN ( 140, 141, 142, 143,
                                                         144 )
                            ) b,
                            FN_GetPowerRangePList(@OperatorId, '') c
                  WHERE     LEFT(a.[ptypeId], LEN(@szPtypeId)) LIKE @szPtypeId
                            + '%'
                            AND EXISTS ( SELECT 1
                                         FROM   FN_GetStockListOfBranch(@OperatorID, @szBTypeId, @szKtypeID) bb
                                         WHERE  a.KtypeId = bb.KtypeId )
                            AND a.[vchcode] = b.[vchcode]
                            AND a.[ptypeid] = c.[typeid]
                ) AS PSONKSON
        ORDER BY [vchcode]
		
        SELECT  vchcode,
                [vchtype],
                qty,
                CASE WHEN qty < 0 THEN ABS(qty)
                     ELSE 0
                END AS qtyout,
                CASE WHEN qty >= 0 THEN qty
                     ELSE 0
                END AS qtyin,
                Total,
                [date],
                [number],
                comment,
                PtypeId,
                RedOld,
                redword
        FROM    #detail11
        ORDER BY vchcode
    END
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--	得到职员的明细
    GetEtype:
--	得到一个单位，一个职员的应收应付款
    IF ( @szAtypeId = @AR_ID )
        OR ( @szAtypeId = @AP_ID ) 
        BEGIN

            SELECT  da.[vchcode],
                    da.[vchtype],
                    ISNULL(da.[total], 0) AS Total,
                    da.[date],
                    da.[atypeid],
                    ISNULL(dn.[number], '') AS [number],
                    ISNULL(dn.[summary], '') AS comment,
                    dn.redold,
                    da.redword
            FROM    ( SELECT    *
                      FROM      DlyA
                      WHERE     @szBeginData <= [Date]
                                AND @szEndData >= [Date]
                                AND ( [atypeId] = @AR_ID
                                      OR [atypeId] = @AP_ID
                                    )
                                AND [etypeid] LIKE @szEtypeId
                                AND [btypeId] LIKE @szBtypeId
                    ) da,
                    ( SELECT    *
                      FROM      DlyNdx
                      WHERE     @szBeginData <= [date]
                                AND @szEndData >= [date]
                    ) dn
            WHERE   da.[vchcode] = dn.[vchcode]
            ORDER BY da.[vchcode]
        END
--	得到职员的回款明细
--	回款统计应为科目为现金、银行，单据为收款单，销售单，销售退货单三种单据
    ELSE 
        BEGIN
            IF @nBSonnum > 0 
                BEGIN

                    SELECT  da.[vchcode],
                            da.[vchtype],
                            da.[atypeid],
                            ISNULL(da.[total], 0) AS Total,
                            da.[date],
                            ISNULL(dn.[number], '') AS [number],
                            ISNULL(dn.[summary], '') AS comment,
                            ISNULL(b.[fullname], '') AS Bfullname,
                            a.[fullname] AS Afullname,
                            v.[fullname] AS Vfullname,
                            dn.redold,
                            da.RedWord
                    FROM    ( SELECT    *
                              FROM      DlyA
                              WHERE     @szBeginData <= [Date]
                                        AND @szEndData >= [Date]
                                        AND ( ( LEFT([atypeid], LEN(@CASH_ID)) = @CASH_ID )
                                              OR ( LEFT([atypeid],
                                                        LEN(@CASH_BANK_ID)) = @CASH_BANK_ID )
                                            )
                                        AND [etypeid] LIKE @szEtypeId
                                        AND LEFT([btypeId], LEN(@szBtypeId)) LIKE @szBtypeId
                            ) da,
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND [vchtype] IN ( @SALEBILL,
                                                           @SALEBACKBILL,
                                                           @GETMONEYBILL, 222,
                                                           224, 250, 12, 13,
                                                           24, 26 )
                            ) dn,
                            btype b,
                            atype a,
                            vchtype v
                    WHERE   da.[btypeId] = b.[typeid]
                            AND da.[atypeid] = a.[typeid]
                            AND da.[vchcode] = dn.[vchcode]
                            AND da.[vchtype] = v.[vchtype]
                    ORDER BY da.[vchcode]
                END
            ELSE 
                BEGIN
                    SELECT  da.[vchcode],
                            da.[vchtype],
                            da.[atypeid],
                            ISNULL(da.[total], 0) AS Total,
                            da.[date],
                            ISNULL(dn.[number], '') AS [number],
                            ISNULL(dn.[summary], '') AS comment,
                            ISNULL(b.[fullname], '') AS Bfullname,
                            a.[fullname] AS Afullname,
                            v.[fullname] AS Vfullname,
                            dn.redold,
                            da.redword
                    FROM    ( SELECT    *
                              FROM      DlyA
                              WHERE     @szBeginData <= [Date]
                                        AND @szEndData >= [Date]
                                        AND ( ( LEFT([atypeid], LEN(@CASH_ID)) = @CASH_ID )
                                              OR ( LEFT([atypeid],
                                                        LEN(@CASH_BANK_ID)) = @CASH_BANK_ID )
                                            )
                                        AND [etypeid] LIKE @szEtypeId
                                        AND [btypeId] LIKE @szBtypeId
                            ) da,
                            ( SELECT    *
                              FROM      DlyNdx
                              WHERE     @szBeginData <= [date]
                                        AND @szEndData >= [date]
                                        AND [vchtype] IN ( @SALEBILL,
                                                           @SALEBACKBILL,
                                                           @GETMONEYBILL, 222,
                                                           224, 250, 12, 13,
                                                           24, 26 )
                            ) dn,
                            btype b,
                            atype a,
                            vchtype v
                    WHERE   da.[btypeId] = b.[typeid]
                            AND da.[atypeid] = a.[typeid]
                            AND da.[vchcode] = dn.[vchcode]
                            AND da.[vchtype] = v.[vchtype]
                    ORDER BY da.[vchcode]
                END
        END
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--	得到进货的明细(包括受托结算)
    GetBuy:

    SELECT  a.[vchcode],
            a.[vchtype],
            ISNULL(a.[qty], 0) AS Qty,
            ISNULL(a.[tax_total], 0) AS Total,
            a.[date],
            ISNULL(b.[number], '') AS [number],
            ISNULL(b.[summary], '') AS comment,
            a.redold,
            a.ptypeid,
            a.btypeid,
            a.ktypeid,
            a.redword
    FROM    Dlydata a,
            dlyndx b
    WHERE   @szBeginData <= a.[date]
            AND @szEndData >= a.[date]
            AND a.vchcode = b.vchcode
            AND a.billtype = 1
            AND a.ptypeid LIKE @szptypeId + '%'
            --AND a.ktypeid LIKE @szKtypeId + '%'
            AND a.btypeid LIKE @szbtypeId + '%'
           -- AND a.BranchId LIKE @Branchid + '%'
           
           AND EXISTS ( SELECT 1 FROM   FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) FilterK WHERE  a.ktypeId = Filterk.KtypeId )
           
            AND EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangePList(@OperatorId, '') FilterP
                         WHERE  a.PtypeId = FilterP.TypeId )    --商品权限         	     
            AND EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangeEList(@OperatorId, '') FilterE
                         WHERE  a.EtypeId = FilterE.TypeId )    --经手人权限
            AND EXISTS ( SELECT 1
                         FROM   FN_GetPowerRangeBCList(@OperatorId, '') FilterBC
                         WHERE  a.branchid = FilterBC.branchid ) --机构权限      										     
    ORDER BY a.[vchcode]
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--	得到进货的明细(不包括受托结算)
    GetBuy1:
    SELECT  a.[vchcode],
            a.[vchtype],
            ISNULL(a.[qty], 0) AS Qty,
            ISNULL(a.[tax_total], 0) AS Total,
            a.[date],
            ISNULL(b.[number], '') AS [number],
            ISNULL(b.[summary], '') AS comment,
            a.ptypeid,
            a.btypeid,
            a.ktypeid,
            b.redold,
            a.redword
    FROM    Dlydata a,
            dlyndx b
    WHERE   @szBeginData <= a.[date]
            AND @szEndData >= a.[date]
            AND a.btypeid LIKE @szbtypeId + '%'
            AND a.billtype = 1
            AND a.[ptypeId] LIKE @szPtypeId + '%'
            AND a.[vchcode] = b.[vchcode]
    ORDER BY a.[vchcode] 
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee

--	得到进货退货的明细
    GetBuyBack:

    SELECT  a.[vchcode],
            a.[vchtype],
            ABS(ISNULL(a.[qty], 0)) AS Qty, 
        --在存储过程中计算增加额和减少额
            ABS(CASE WHEN ISNULL(a.[qty], 0) > 0 THEN ISNULL(a.[qty], 0)
                     ELSE 0
                END) AS InStock,
            ABS(CASE WHEN ISNULL(a.[qty], 0) < 0 THEN ISNULL(a.[qty], 0)
                     ELSE 0
                END) AS OutStock,
            ABS(ISNULL(a.[tax_total], 0)) AS Total,
            a.[date],
            ISNULL(b.[number], '') AS [number],
            ISNULL(b.[summary], '') AS comment,
            a.btypeid,
            a.ktypeid,
            a.ptypeid,
            b.redold,
            a.RedWord
    FROM    Dlydata a,
            dlyndx b
    WHERE   @szBeginData <= a.[date]
            AND @szEndData >= a.[date]
            AND a.[ktypeid] LIKE @szKtypeId + '%'
            AND a.btypeid LIKE @szbtypeId + '%'
            AND a.billtype = 1
            AND a.[ptypeId] LIKE @szPtypeId + '%'
            AND a.[vchcode] = b.[vchcode]
            AND a.vchtype = 6
            AND a.btypeid LIKE @szbtypeid + '%'
    ORDER BY a.[vchcode]

    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--	得到进货退货分析的明细（暂时无用）
    GetBuyandback:

    SELECT  a.[vchcode],
            a.[vchtype],
            ABS(ISNULL(a.[qty], 0)) AS Qty,
            ABS(ISNULL(a.[tax_total], 0)) AS Total,
            a.[date],
            ISNULL(b.[number], '') AS [number],
            ISNULL(b.[summary], '') AS comment,
            a.ptypeid,
            a.btypeid,
            a.ktypeid,
            b.redold,
            a.RedWord
    FROM    Dlydata a,
            DlyNdx b
    WHERE   @szBeginData <= a.[date]
            AND @szEndData >= a.[date]
            AND a.billtype = 1
            AND a.[ktypeid] LIKE @szKtypeId + '%'
            AND a.btypeid LIKE @szbtypeId + '%'
            AND a.[ptypeId] LIKE @szPtypeId + '%'
            AND a.[vchcode] = b.[vchcode]
    ORDER BY a.[vchcode]
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--           得到销售换货的明细
    GetSaleExchange: 
	          
    SELECT  a.[vchcode],
            a.[vchtype],
            ABS(ISNULL(a.[qty], 0)) AS Qty,
            ABS(ISNULL(a.[tax_total], 0)) AS Total,
            a.[date],
            ISNULL(b.[number], '') AS [number],
            ISNULL(b.[summary], '') AS comment,
            a.ptypeid,
            a.btypeid,
            a.ktypeid,
            b.redold,
            a.RedWord--,b.BarterRate,
    FROM    Dlydata a,
            DlyNdx b
    WHERE   a.[ptypeId] LIKE @szPtypeId + '%'
            AND @szBeginData <= a.[date]
            AND @szEndData >= a.[date]
            AND a.[vchcode] = b.[vchcode]
            AND a.Btypeid LIKE @szBtypeId + '%'
            AND a.vchtype = 24
            AND b.BarterType = 0
            AND a.usedtype = 1
    UNION ALL
    SELECT  a.[vchcode],
            a.[vchtype],
            ABS(ISNULL(a.[qty], 0)) AS Qty,
            ABS(ISNULL(a.[tax_total], 0)) AS Total,
            a.[date],
            ISNULL(b.[number], '') AS [number],
            ISNULL(b.[summary], '') AS comment,
            a.ptypeid,
            a.btypeid,
            a.ktypeid,
            b.redold,
            a.RedWord--,b.BarterRate
    FROM    Dlydata a,
            DlyNdx b
    WHERE   a.[ptypeId] LIKE @szPtypeId + '%'
            AND @szBeginData <= a.[date]
            AND @szEndData >= a.[date]
            AND a.[vchcode] = b.[vchcode]
            AND usedtype = CASE WHEN a.vchtype IN ( 222, 224 ) THEN 1
                                ELSE usedtype
                           END
            AND a.Btypeid LIKE @szBtypeId + '%'
            AND a.vchtype IN ( 45, 13, 224 )
            AND b.BarterType = 0
    ORDER BY a.vchcode
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--         得到加盟店零售明细s
    GetJoinSale:      
    IF @szKtypeID = '%%' 
        SET @szKtypeID = ''
    IF @szBtypeID = '%%' 
        SET @szBtypeID = ''
    SELECT  a.[vchcode],
            a.[vchtype],
            ABS(( CASE WHEN ISNULL(a.[qty], 0) > 0 THEN ISNULL(a.[qty], 0)
                       ELSE 0
                  END )) AS InStock,
            ABS(( CASE WHEN ISNULL(a.[qty], 0) < 0 THEN ISNULL(a.[qty], 0)
                       ELSE 0
                  END )) AS OutStock,
            ABS(ISNULL(a.[tax_total], 0)) AS Total,
            a.[date],
            ISNULL(b.[number], '') AS [number],
            ISNULL(b.[summary], '') AS comment,
            a.ptypeid,
            a.btypeid,
            a.ktypeid,
            b.redold,
            a.RedWord
    FROM    DlyData a,
            DlyNdx b
    WHERE   LEFT(a.[ptypeId], LEN(@szPtypeId)) = @szPtypeId
            AND a.vchtype IN ( 226, 227 )
            AND @szBeginData <= a.[date]
            AND @szEndData >= a.[date]
            AND a.[vchcode] = b.[vchcode]
            AND EXISTS ( SELECT 1
                         FROM   FN_GetStockListOfBranch(@OperatorID,
                                                        @szBTypeId, @szKtypeID) bb
                         WHERE  a.KtypeId = bb.KtypeId )
    ORDER BY a.vchcode
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
--	得到加盟店配货订单明细
    Getjoinorder:
    SELECT  b.[vchcode],
            b.[vchtype],
            ISNULL(b.[qty], 0) AS Qty,
            ISNULL(b.[tax_total], 0) AS Total,
            b.[date],
            ISNULL(d.[number], '') AS [number],
            ISNULL(d.[summary], '') AS comment,
            b.ptypeid,
            b.btypeid,
            b.ktypeid,
            '' AS redword,
            '' AS redold
    FROM    BakDlyorder b,
            dlyndxorder d
    WHERE   @szBeginData <= b.date
            AND @szEndData >= b.date
            AND b.btypeid LIKE @szbtypeId + '%'
            AND b.ktypeid LIKE @szKtypeId + '%'
            AND b.vchcode = d.vchcode
            AND b.vchtype IN ( 221, 223 )
            AND b.[ptypeId] LIKE @szPtypeId + '%'
    ORDER BY b.[vchcode]
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
-- 	得到自营店配货订单明细
    GetBuyorder:
	
    SELECT  a.[vchcode],
            a.[vchtype],
            -( ISNULL(a.[qty], 0) ) AS Qty,
            ISNULL(a.[tax_total], 0) AS Total,
            a.[date],
            ISNULL(d.[number], '') AS [number],
            ISNULL(d.[summary], '') AS comment,
            a.ptypeid,
            a.btypeid,
            a.ktypeid,
            '' AS redword,
            '' AS redold
    FROM    BakDlyorder a,
            dlyndxorder d
    WHERE   @szBeginData <= a.date
            AND @szEndData >= a.date
            AND a.btypeid LIKE @szbtypeId + '%'
            AND a.ktypeid LIKE @szKtypeId + '%'
            AND a.vchcode = d.vchcode
            AND a.[ptypeId] LIKE @szPtypeId + '%'
            AND a.vchtype IN ( 211, 214 )
    ORDER BY a.[vchcode]
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
	
    GetBtypeSaleAnalyse:
    SELECT  ds.[vchcode],
            ds.[vchtype],
            SUM(ABS(( CASE WHEN ISNULL(dsd.[qty], 0) > 0
                           THEN ISNULL(dsd.[qty], 0)
                           ELSE 0
                      END ))) AS InStock,
            SUM(ABS(( CASE WHEN ISNULL(dsd.[qty], 0) < 0
                           THEN ISNULL(dsd.[qty], 0)
                           ELSE 0
                      END ))) AS OutStock,
            -SUM(( ISNULL(( dsd.[tax_total] ), 0) )) AS Total,
            ds.[date],
            ISNULL(d.[number], '''') AS [number],
            ds.redold,
            ISNULL(d.[summary], '''') AS comment,
            Ptypeid,
            ds.btypeid,
            ds.Ktypeid,
            ds.RedWord
    FROM    Dlydata ds
            LEFT JOIN dlyndx d ON ds.vchcode = d.vchcode
            LEFT JOIN dlydatadetail dsd ON ds.dlyorder = dsd.dlyorder
    WHERE   ds.BillType = 2
            AND ptypeid LIKE @szPtypeId + '%'
            --AND ds.branchid LIKE @branchid + '%'
            AND ds.usedtype = CASE WHEN ds.vchtype IN ( 222, 224 ) THEN 1
                                ELSE ds.usedtype
                           END
            --AND ds.ktypeid LIKE @szKtypeId + '%'
            AND EXISTS ( SELECT 1 FROM   FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) FilterK WHERE  ds.ktypeId = Filterk.KtypeId )
            AND ds.Dtypeid LIKE @deptid + '%'
            AND ds.etypeid LIKE @szEtypeid + '%'
            AND ( CASE WHEN ds.vchtype IN ( 100, 101 ) THEN ds.ktypeid
                       ELSE ds.Btypeid
                  END ) LIKE @szBtypeid + '%'
            AND ds.date BETWEEN @szBeginData AND @szEndData
    GROUP BY ds.vchcode,
            ds.vchtype,
            ds.[date],
            d.number,
            ds.redold,
            d.summary,
            Ptypeid,
            ds.btypeid,
            ds.Ktypeid,
            ds.RedWord
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
      
    GetRetailSale:
    SELECT  ds.[vchcode],
            ds.[vchtype],
            SUM(ABS(( CASE WHEN ISNULL(dsd.[qty], 0) > 0
                           THEN ISNULL(dsd.[qty], 0)
                           ELSE 0
                      END ))) AS InStock,
            SUM(ABS(( CASE WHEN ISNULL(dsd.[qty], 0) < 0
                           THEN ISNULL(dsd.[qty], 0)
                           ELSE 0
                      END ))) AS OutStock,
            -SUM(( ISNULL(( dsd.[tax_total] ), 0) )) AS Total,
            ds.[date],
            ISNULL(d.[number], '''') AS [number],
            ISNULL(d.[summary], '''') AS comment,
            Ptypeid,
            ds.btypeid,
            ds.Ktypeid,
            ds.redold,
            ds.RedWord
    FROM    Dlydata ds
            LEFT JOIN Btype b ON ds.Btypeid = b.typeid
            LEFT JOIN dlyndx d ON ds.vchcode = d.vchcode
            LEFT JOIN FN_GetPowerRangePList(@OperatorId, '') p ON ds.ptypeid = p.typeid
            LEFT JOIN dlydatadetail dsd ON ds.dlyorder = dsd.dlyorder
    WHERE   ds.vchtype IN ( 12, 13, 100, 101 )
            --AND ds.branchid LIKE @branchid + '%'
            AND p.stop = CASE @ifstop
                           WHEN '1' THEN p.stop
                           ELSE 0
                         END
            AND ds.btypeid LIKE @szBtypeid + '%'
            AND ds.Dtypeid LIKE @deptid + '%'
            AND ( ( ( CASE @CustType
                        WHEN '1' THEN CustValue1
                        WHEN '2' THEN CustValue2
                        WHEN '3' THEN CustValue3
                        WHEN '4' THEN CustValue4
                        WHEN '5' THEN CustValue5
                        ELSE CustValue6
                      END ) IN ( SELECT typeid
                                 FROM   GetResultTableLZL(@SaleTraitName) )
                    AND @CustType <> ''
                  )
                  OR ( @CustType = '' )
                )
            AND ptypeid LIKE @szPtypeId + '%'
           -- AND ds.ktypeid LIKE @szKtypeId + '%'
           AND EXISTS ( SELECT 1 FROM   FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) FilterK WHERE  ds.ktypeId = Filterk.KtypeId )
            AND ds.date BETWEEN @szBeginData AND @szEndData
    GROUP BY ds.vchcode,
            ds.vchtype,
            ds.[date],
            d.number,
            d.summary,
            Ptypeid,
            ds.btypeid,
            ds.Ktypeid,
            ds.redold,
            ds.RedWord
    IF @@rowcount = 0 
        GOTO error2
    GOTO succee
      
--	得到销售的明细
    GetSale:
    BEGIN  --销售(包括已经结算的商场专柜零售、退货单)
        SELECT  a.[vchcode],
                a.[vchtype],
                a.ktypeid,
                a.ptypeid,
                a.btypeid,
                SUM(ABS(( CASE WHEN ISNULL(ad.[qty], 0) > 0
                               THEN ISNULL(ad.[qty], 0)
                               ELSE 0
                          END ))) AS InStock,
                SUM(ABS(( CASE WHEN ISNULL(ad.[qty], 0) < 0
                               THEN ISNULL(ad.[qty], 0)
                               ELSE 0
                          END ))) AS OutStock,
                -SUM(ISNULL(ad.[tax_total], 0)) AS Total,
                a.[date],
                SUM(ad.qty) AS cccc,
                a.RedOld,
                a.RedWord
        FROM    Dlydata a,
                FN_GetPowerRangePList(@OperatorId, '') p,
                dlydatadetail ad
        WHERE   billtype = 2
                AND @szBeginData <= [date]
                AND a.ptypeid = p.typeid
                AND a.dlyorder = ad.dlyorder
                --AND a.branchid LIKE @branchid + '%'
                AND EXISTS ( SELECT 1 FROM   FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) FilterK WHERE  a.ktypeId = Filterk.KtypeId )
                AND @szEndData >= [date]
                AND Dtypeid LIKE @deptid + '%'
                AND btypeid LIKE @szBtypeid + '%'
                --AND ktypeid LIKE @szKtypeId + '%'
                AND etypeid LIKE @szetypeid + '%'
                AND ( ( ( CASE @CustType
                            WHEN '1' THEN CustValue1
                            WHEN '2' THEN CustValue2
                            WHEN '3' THEN CustValue3
                            WHEN '4' THEN CustValue4
                            WHEN '5' THEN CustValue5
                            ELSE CustValue6
                          END ) IN ( SELECT typeid
                                     FROM   GetResultTableLZL(@SaleTraitName) )
                        AND @CustType <> ''
                      )
                      OR ( @CustType = '' )
                    )
                AND LEFT(a.[ptypeId], LEN(@szPtypeId + '%')) LIKE @szPtypeId
                + '%'
                AND p.stop = CASE @ifstop
                               WHEN 1 THEN p.stop
                               ELSE 0
                             END
                AND a.usedtype = CASE WHEN vchtype IN ( 222, 224 ) THEN 1
                                    ELSE a.usedtype
                               END
			--and a.vchtype in (11,45,12,13,222,224,100,101,24)  
        GROUP BY a.vchcode,
                vchtype,
                date,
                a.ktypeid,
                a.ptypeid,
                a.btypeid,
                a.RedOld,
                a.RedWord
        ORDER BY a.vchcode
        GOTO succee
    END
   
--加盟店销售统计明细
    GetJoin:
    SELECT  a.[vchcode],
            a.[vchtype],
            a.ktypeid,
            a.ptypeid,
            a.btypeid,
            SUM(ABS(( CASE WHEN ISNULL(a.[qty], 0) > 0 THEN ISNULL(a.[qty], 0)
                           ELSE 0
                      END ))) AS InStock,
            SUM(ABS(( CASE WHEN ISNULL(a.[qty], 0) < 0 THEN ISNULL(a.[qty], 0)
                           ELSE 0
                      END ))) AS OutStock,
            -SUM(ISNULL(a.[tax_total], 0)) AS Total,
            a.[date],
            SUM(qty) AS cccc,
            a.RedOld,
            a.RedWord
    FROM    Dlydata a,
            FN_GetPowerRangePList(@OperatorId, '') p
    WHERE   billtype = 2
            AND @szBeginData <= [date]
            AND a.ptypeid = p.typeid
            AND @szEndData >= [date]
            AND Dtypeid LIKE @deptid + '%'
            AND btypeid LIKE @szBtypeid + '%'
            AND ktypeid LIKE @szKtypeId + '%'
            AND ( ( ( CASE @CustType
                        WHEN '1' THEN CustValue1
                        WHEN '2' THEN CustValue2
                        WHEN '3' THEN CustValue3
                        WHEN '4' THEN CustValue4
                        WHEN '5' THEN CustValue5
                        ELSE CustValue6
                      END ) IN ( SELECT typeid
                                 FROM   GetResultTableLZL(@SaleTraitName) )
                    AND @CustType <> ''
                  )
                  OR ( @CustType = '' )
                )
            AND LEFT(a.[ptypeId], LEN(@szPtypeId + '%')) LIKE @szPtypeId + '%'
            AND p.stop = CASE @ifstop
                           WHEN 1 THEN p.stop
                           ELSE 0
                         END
            AND a.usedtype = CASE WHEN vchtype IN ( 222, 224 ) THEN 1
                                ELSE a.usedtype
                           END
            AND a.vchtype IN ( 222, 224 )
    GROUP BY a.vchcode,
            vchtype,
            date,
            a.ktypeid,
            a.ptypeid,
            a.btypeid,
            a.RedOld,
            a.RedWord
    ORDER BY a.vchcode
    GOTO succee
	
    GetShop:
    BEGIN
        SELECT  a.[vchcode],
                a.[vchtype],
                a.ktypeid,
                a.ptypeid,
                a.btypeid,
                SUM(ABS(( CASE WHEN ISNULL(a.[qty], 0) > 0
                               THEN ISNULL(a.[qty], 0)
                               ELSE 0
                          END ))) AS InStock,
                SUM(ABS(( CASE WHEN ISNULL(a.[qty], 0) < 0
                               THEN ISNULL(a.[qty], 0)
                               ELSE 0
                          END ))) AS OutStock,
                -SUM(ISNULL(a.[tax_total], 0)) AS Total,
                a.[date],
                SUM(qty) AS cccc,
                a.RedOld,
                a.RedWord
        FROM    Dlydata a,
                FN_GetPowerRangePList(@OperatorId, '') p
        WHERE   billtype = 2
                AND @szBeginData <= [date]
                AND a.ptypeid = p.typeid
                AND @szEndData >= [date]
                AND Dtypeid LIKE @deptid + '%'
                AND btypeid LIKE @szBtypeid + '%'
                AND ktypeid LIKE @szKtypeId + '%'
                AND ( ( ( CASE @CustType
                            WHEN '1' THEN CustValue1
                            WHEN '2' THEN CustValue2
                            WHEN '3' THEN CustValue3
                            WHEN '4' THEN CustValue4
                            WHEN '5' THEN CustValue5
                            ELSE CustValue6
                          END ) IN ( SELECT typeid
                                     FROM   GetResultTableLZL(@SaleTraitName) )
                        AND @CustType <> ''
                      )
                      OR ( @CustType = '' )
                    )
                AND LEFT(a.[ptypeId], LEN(@szPtypeId + '%')) LIKE @szPtypeId
                + '%'
                AND p.stop = CASE @ifstop
                               WHEN 1 THEN p.stop
                               ELSE 0
                             END
                AND a.vchtype IN ( 100, 101 )
        GROUP BY a.vchcode,
                vchtype,
                date,
                a.ktypeid,
                a.ptypeid,
                a.btypeid,
                a.RedOld,
                a.RedWord
        ORDER BY a.vchcode
        GOTO succee
        IF @@rowcount = 0 
            GOTO error2
        GOTO succee
    END
	
    GetSalepreferential:
    IF ( @nBSonnum > 0 )
        OR ( @neSonnum > 0 ) 
        BEGIN
            SELECT  S.vchCode,
                    s.vchtype,
                    s.Date,
                    s.bTypeID,
                    s.eTypeID,
                    ISNULL(n.[summary], '') AS comment,
                    n.Number,
                    ISNULL(SUM(a.Total), 0) AS yTotal,
                    ISNULL(SUM(-s.Tax_Total), 0) AS TaxTotal,
                    ISNULL(SUM(-s.Tax_Total) - SUM(a.Total), 0) AS Total,
                    n.Number,
                    ISNULL(b.FullName, '') AS bfullName,
                    ISNULL(e.FullName, '') AS efullName,
                    s.RedOld,
                    s.RedWord
            FROM    ( SELECT    vchcode,
                                vchtype,
                                date,
                                btypeid,
                                etypeid,
                                SUM(Tax_Total) AS Tax_Total,
                                redold,
                                redword
                      FROM      Dlydata
                      WHERE     Date >= @szBeginData
                                AND Date <= @szEndData
                                AND BTypeID LIKE @szBTypeID + '%'
                                AND ETypeID LIKE @szETypeID + '%'
                                AND KTypeID LIKE @szKTypeID
                      GROUP BY  vchcode,
                                vchtype,
                                date,
                                btypeid,
                                etypeid,
                                redword,
                                redold
                    ) AS S
                    LEFT OUTER JOIN ( SELECT    VchCode,
                                                Total
                                      FROM      DlyA
                                      WHERE     ATypeID = '000040000100004'
                                                AND VchType IN ( 24, 222, 224, 11, 45, 12, 13 )
                                                AND Date >= @szBeginData
                                                AND Date <= @szEndData
                                                AND BTypeID LIKE @szBTypeID
                                                + '%'
                                                AND ETypeID LIKE @szETypeID
                                                + '%'
                                    ) AS a ON s.VchCode = A.VchCode
                    LEFT OUTER JOIN DlyNdx n ON s.VchCode = n.VchCode
                    LEFT OUTER JOIN BType b ON s.BTypeID = b.TypeID
                    LEFT OUTER JOIN Employee e ON s.ETypeID = e.TypeID
            WHERE   s.BTypeID LIKE @szBTypeID + '%'
                    AND s.ETypeID LIKE @szETypeID + '%'
            GROUP BY s.vchCode,
                    s.vchtype,
                    s.Date,
                    s.bTypeID,
                    s.eTypeID,
                    n.summary,
                    n.Number,
                    b.fullName,
                    e.fullName,
                    s.RedOld,
                    s.RedWord
            ORDER BY S.vchcode
        END
    ELSE 
        BEGIN
            SELECT  s.vchCode,
                    s.vchtype,
                    s.Date,
                    s.bTypeID,
                    s.eTypeID,
                    ISNULL(n.[summary], '') AS comment,
                    ISNULL(SUM(a.Total), 0) AS yTotal,
                    ISNULL(SUM(-s.Tax_Total), 0) AS TaxTotal,
                    ISNULL(SUM(-s.Tax_Total) - SUM(a.Total), 0) AS Total,
                    n.Number,
                    n.Summary,
                    ISNULL(b.FullName, '') AS bfullName,
                    ISNULL(e.FullName, '') AS efullName,
                    s.RedOld,
                    s.RedWord
            FROM    ( SELECT    vchcode,
                                vchtype,
                                date,
                                btypeid,
                                etypeid,
                                SUM(Tax_Total) AS Tax_Total,
                                RedOld,
                                RedWord
                      FROM      dlydata
                      WHERE     Date >= @szBeginData
                                AND Date <= @szEndData
                                AND BTypeID LIKE @szBTypeID + '%'
                                AND ETypeID LIKE @szETypeID + '%'
                      GROUP BY  vchcode,
                                vchtype,
                                date,
                                btypeid,
                                etypeid,
                                RedOld,
                                RedWord
                    ) s
                    LEFT OUTER JOIN ( SELECT    VchCode,
                                                Total
                                      FROM      DlyA
                                      WHERE     ATypeID = '000040000100004'
                                                AND VchType IN ( 24, 222, 224, 11, 45, 12, 13 )
                                                AND Date >= @szBeginData
                                                AND Date <= @szEndData
                                                AND BTypeID LIKE @szBTypeID
                                                AND ETypeID LIKE @szETypeID
                                    ) a ON a.VchCode = s.VchCode
                    LEFT OUTER JOIN DlyNdx n ON s.VchCode = n.VchCode
                    LEFT OUTER JOIN BType b ON s.BTypeID = b.TypeID
                    LEFT OUTER JOIN Employee e ON s.ETypeID = e.TypeID
            GROUP BY s.vchCode,
                    s.vchtype,
                    s.Date,
                    s.bTypeID,
                    s.eTypeID,
                    n.[summary],
                    n.Number,
                    s.RedOld,
                    s.RedWord,
                    b.fullName,
                    e.fullName
            ORDER BY s.vchcode
        END
    IF @@ROWCOUNT = 0 
        GOTO error2
    GOTO succee
	
    GetExp:
    IF @szPtypeId = 'B' 
        SELECT  @szEtypeid = ''
    IF @szPtypeid = 'E' 
        SELECT  @szBtypeid = ''
    SELECT  a.[vchcode],
            a.[vchtype],
            a.[atypeid],
            a.[date],
            b.redold,
            a.[Total],
            ISNULL(b.[number], '') AS number,
            ISNULL(b.[summary], '') AS comment,
            a.btypeid,
            a.ktypeid,
            b.[redold],
            b.RedWord,
            b.etypeid
    FROM    ( SELECT    *
              FROM      DlyA
              WHERE     Date >= @szBeginData
                        AND Date <= @szendData
                        AND LEFT([atypeId], LEN(@Business_EXPENSE_ID)) LIKE @Business_EXPENSE_ID
                        + '%'
                        AND LEFT([etypeId], LEN(@szetypeid)) LIKE @szetypeid
                        + '%'
                        AND LEFT([btypeId], LEN(@szbtypeId)) LIKE @szbtypeId
                        + '%'
            ) a
            LEFT JOIN --and Left([btypeId], Len(@szbtypeId)) like @szbtypeId+'%') a,
            ( SELECT    *
              FROM      DlyNdx
              WHERE     [date] >= @szBeginData
                        AND Date <= @szendData
            ) b ON a.vchcode = b.vchcode
    ORDER BY a.[vchcode]
    IF @@ROWCOUNT = 0 
        GOTO error2
    GOTO succee

    succee:
    RETURN 0
    error1:
    SELECT  'A'
    RETURN -103
    error2:
    SELECT  'B'
    RETURN -101




GO
 SET QUOTED_IDENTIFIER OFF 
GO
 SET ANSI_NULLS ON 
GO

--------------------------2011-08-18修改，仓库分支中增加一个返回的BCTYPEID，BUG号502------------------
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FzGetGroupList]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FzGetGroupList]
GO

--  ********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：F_B_GetGroupList                                                   
--  ||   过程功能：得到基本信息的类别树  
--  ||=========================================================================================  
--  ||   参数说明：  参数名称         类型            意义                     输入输出  
--  ||            -----------------------------------------------------------------------------  
--  ||            @cMode  char(5)  :基本信息类型参数   IN  
--  ||            @szTypeid  varchar(50) :根节点Typeid   IN  
--  ||=========================================================================================  

/*
作者：cqhua
日期：2011-08-18
修改原因：默认仓库字段参数改了 defaultstock==>IsDefault
2011-08-29 会计科目加权限
*/
   
CREATE PROCEDURE FzGetGroupList
    (
      @OperatorID VARCHAR(50),
      @cMode VARCHAR(5),
      @szTypeid VARCHAR(50),
      @szFullName VARCHAR(66) = '',
      @szUserCode VARCHAR(26) = '',
      @szStopDate VARCHAR(10) = '',
      @szBarCode VARCHAR(50) = '',  --特殊说明下，职员选择时@szBarCode代表的职员所属的机构Id，不要了
      @szName VARCHAR(66) = '',
      @szIssueDate VARCHAR(10) = '',
      @SearchFlag BIT,
      @BranchId VARCHAR(50) = '00001',
      @FZCSCASHBANK CHAR(1) = ''
    )
AS 
/*
alter by hww 2011年10月12日15:49:08 增加参数@FZCSCASHBANK，区别是否是CS中的现金银行 1 := 是
*/
    SET nocount ON  
    DECLARE @con INT  
    SELECT  @con = stats
    FROM    syscon
    WHERE   [order] = 36  
    DECLARE @TableName VARCHAR(100)
    SET @TableName = 'Btype '   
--alter by hww 2011年9月29日16:26:00 CS在会计科目上是没有权限，已总部机构为准
if @cMode = 'A' and exists(select * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZCS')
BEGIN
	SELECT @OperatorID = '00000',@BranchId = '0000100001'
	--特殊处理现金科目和银行帐户同时显示
	IF @FZCSCASHBANK = '1' 
	BEGIN
		IF @SearchFlag = 1 --list
		BEGIN
		    SELECT  	Typeid AS Atypeid,
                    		TYPEID,
                    		PARID,
                    		SONNUM,
                    		USERCODE,
                    		FULLNAME,
                    		[NAME],
                    		NAMEPY,
                    		COMMENT,
                    		CASE WHEN @BranchId = '0000100001' THEN '00001'
                         	ELSE branchid
                    		END AS branchid,
                    		rec,
                    		0 AS paridstop
            			FROM    atype p
            		WHERE   sonnum = 0	
            		AND     branchid = @BranchId
            		AND     (TypeID LIKE '0000100003%' OR TypeID LIKE '0000100004%')
            		AND 	p.fullname LIKE '%' + @szFullName + '%'
                        AND 	usercode LIKE '%' + @szUserCode + '%'
			and     deleted = 0
		END
		ELSE --tree
		BEGIN
		    SELECT  	Typeid AS Atypeid,
                    		TYPEID,
                    		PARID,
                    		SONNUM,
                    		USERCODE,
                    		FULLNAME,
                    		[NAME],
                    		NAMEPY,
                    		COMMENT,
                    		CASE WHEN @BranchId = '0000100001' THEN '00001'
                         	ELSE branchid
                    		END AS branchid,
                    		rec,
                    		0 AS paridstop
            			FROM    atype p
            		WHERE   branchid = @BranchId
			AND     (TypeID LIKE '0000100003%' OR TypeID LIKE '0000100004%')
            		AND	parid  =  @szTypeid 
            		and 	deleted = 0
            		AND 	p.fullname LIKE '%' + @szFullName + '%'
                        AND 	usercode LIKE '%' + @szUserCode + '%'
			and     deleted = 0
		END
	RETURN 
	END
END
    IF @cMode = 'A' 
        IF @SearchFlag = 1 
            SELECT  Typeid AS Atypeid,
                    TYPEID,
                    PARID,
                    SONNUM,
                    USERCODE,
                    FULLNAME,
                    [NAME],
                    NAMEPY,
                    COMMENT,
                    CASE WHEN @BranchId = '0000100001' THEN '00001'
                         ELSE branchid
                    END AS branchid,
                    rec,
                    0 AS paridstop
            FROM    FN_GetPowerRangeAList(@OperatorID, @szTypeid,@BranchId) p
            WHERE   DELETED = 0
                    AND ( p.fullname LIKE '%' + @szFullName + '%'
                          AND usercode LIKE '%' + @szUserCode + '%'
                        )
            ORDER BY CASE WHEN @con = 0 THEN TYPEID
                          ELSE usercode
                     END  
        ELSE 
        	IF LEFT(@szTypeid,10)='0000100003' OR LEFT(@szTypeid,10)='0000100004'
        		SET @cMode = 'AA' 
        	ELSE
            SELECT  Typeid AS Atypeid,
                    TYPEID,
                    PARID,
                    SONNUM,
                    USERCODE,
                    FULLNAME,
                    [NAME],
                    NAMEPY,
                    COMMENT,
                    CASE WHEN @BranchId = '0000100001' THEN '00001'
                         ELSE branchid
                    END AS branchid,
                    rec,
                    0 AS paridstop
            FROM    FN_GetPowerRangeATree(@OperatorID, @szTypeid,@BranchId) p
            WHERE   parid = @szTypeid
                    AND DELETED = 0
                    AND ( p.fullname LIKE '%' + @szFullName + '%'
                          AND usercode LIKE '%' + @szUserCode + '%'
                        )
                       
            ORDER BY CASE WHEN @con = 0 THEN TYPEID
                          ELSE usercode
                     END 

--银行 + 现金
    IF @cMode = 'AA' 
        IF @szTypeid = '00001' 
            IF @SearchFlag = 1 
                SELECT  Typeid AS Atypeid,
                        TYPEID,
                        PARID,
                        SONNUM,
                        USERCODE,
                        FULLNAME,
                        [NAME],
                        NAMEPY,
                        COMMENT,
                        CASE WHEN @BranchId = '0000100001' THEN '00001'
                             ELSE branchid
                        END AS branchid,
                        rec,
                        0 AS paridstop
                FROM    FN_GetPowerRangeAList(@OperatorID, @szTypeid,@BranchId) p
                WHERE   ( typeid LIKE '0000100003%'
                          OR Typeid LIKE '0000100004%'
                        )
                        AND sonnum = 0
                        AND LEFT(typeid, LEN(@szTypeid)) = @szTypeid
                        AND DELETED = 0
                        AND ( p.fullname LIKE '%' + @szFullName + '%'
                              AND usercode LIKE '%' + @szUserCode + '%'
                            )
                        AND BranchID LIKE @BranchId + '%'
                ORDER BY CASE WHEN @con = 0 THEN TYPEID
                              ELSE usercode
                         END  
            ELSE 
                SELECT  Typeid AS Atypeid,
                        TYPEID,
                        PARID,
                        SONNUM,
                        USERCODE,
                        FULLNAME,
                        [NAME],
                        NAMEPY,
                        COMMENT,
                        CASE WHEN @BranchId = '0000100001' THEN '00001'
                             ELSE branchid
                        END AS branchid,
                        rec,
                        0 AS paridstop
                FROM    FN_GetPowerRangeATree(@OperatorID, @szTypeid,@BranchId) p
                WHERE   ( typeid LIKE '0000100003%'
                          OR Typeid LIKE '0000100004%'
                        )
                        AND parid = @szTypeid
                        
                        AND DELETED = 0
                        AND ( p.fullname LIKE '%' + @szFullName + '%'
                              AND usercode LIKE '%' + @szUserCode + '%'
                            )
                        AND BranchID LIKE @BranchId + '%'
                ORDER BY CASE WHEN @con = 0 THEN TYPEID
                              ELSE usercode
                         END 
        ELSE 
            IF @SearchFlag = 1 
                SELECT  Typeid AS Atypeid,
                        TYPEID,
                        PARID,
                        SONNUM,
                        USERCODE,
                        FULLNAME,
                        [NAME],
                        NAMEPY,
                        COMMENT,
                        CASE WHEN @BranchId = '0000100001' THEN '00001'
                             ELSE branchid
                        END AS branchid,
                        rec,
                        0 AS paridstop
                FROM    FN_GetPowerRangeAList(@OperatorID, @szTypeid,@BranchId) p
                WHERE   sonnum = 0
                        AND LEFT(typeid, LEN(@szTypeid)) = @szTypeid
                        AND DELETED = 0
                        AND ( p.fullname LIKE '%' + @szFullName + '%'
                              AND usercode LIKE '%' + @szUserCode + '%'
                            )
                        AND BranchID LIKE @BranchId + '%'
                ORDER BY CASE WHEN @con = 0 THEN TYPEID
                              ELSE usercode
                         END  
            ELSE 
                SELECT  Typeid AS Atypeid,
                        TYPEID,
                        PARID,
                        SONNUM,
                        USERCODE,
                        FULLNAME,
                        [NAME],
                        NAMEPY,
                        COMMENT,
                        CASE WHEN @BranchId = '0000100001' THEN '00001'
                             ELSE branchid
                        END AS branchid,
                        rec,
                        0 AS paridstop
                FROM    FN_GetPowerRangeATree(@OperatorID, @szTypeid,@BranchId) p
                WHERE   parid = @szTypeid
                        AND DELETED = 0
                        AND ( p.fullname LIKE '%' + @szFullName + '%'
                              AND usercode LIKE '%' + @szUserCode + '%'
                            )
                        AND BranchID LIKE @BranchId + '%'
                ORDER BY CASE WHEN @con = 0 THEN TYPEID
                              ELSE usercode
                         END  


    IF @cMode = 'B' 
        IF @SearchFlag = 0 
            SELECT  b.typeid AS btypeid,
                    B.TYPEID,
                    B.PARID,
                    B.SONNUM,
                    B.USERCODE,
                    B.FULLNAME,
                    B.[NAME],
                    B.NAMEPY,
                    B.COMMENT,
                    B.POSTCODE,
                    B.PERSON,
                    B.TAXNo,
                    B.FAXno,
                    B.BANK,
                    B.Account,
                    B.ADDRESS,
                    b.Tel1,
                    b.tel2,
                    b.netaddress,
                    b.email,
                    b.CheckAndAccept,
                    b.BarterRate,
                    b.BarterTerm,
                    b.usertype,
                    b.branchid,
                    b.[Stop],
		    Case b.[stop] when 1 then '√' else ' ' end as StopMark,
                    --0 AS paridstop
                    ISNULL(( SELECT TOP 1
                                    [stop]
                             FROM   dbo.Btype
                             WHERE  typeid = @szTypeid
                           ), 0) AS paridstop
                           ,b.Person+b.Tel2 as persona 
                           ,b.Personb+b.Telb as personb
                           ,b.Personc+b.Telc as personc,b.wuliu
            FROM    FN_GetPowerRangeBTree(@OperatorID, @szTypeid,
                                          '1,2,3,4,6,7') B
            WHERE   ( ( @SearchFlag = 1
                        AND sonnum = 0
                        AND LEFT(typeid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND parid = @szTypeid
                         )
                    )
                    AND DELETED = 0
                    AND BranchID LIKE @BranchId + '%'
                    AND 
                    (
                    		BranchID like '00001%'
                    		OR
                    		(
                    			BranchID LIKE '00004%'
                    			AND
                    			BranchID IN ( SELECT BranchID FROM dbo.FN_GetPowerRangeBCList(@OperatorID  ,@BranchID ) )
                    		)
												OR
												(
													exists(select * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZCS')													
												)
                    )
                    AND ( fullname LIKE '%' + @szFullName + '%'
                          AND usercode LIKE '%' + @szUserCode + '%'
                        )
            ORDER BY CASE WHEN @con = 0 THEN TYPEID
                          ELSE usercode
                     END  
	
        ELSE 
            SELECT  b.typeid AS btypeid,
                    B.TYPEID,
                    B.PARID,
                    B.SONNUM,
                    B.USERCODE,
                    B.FULLNAME,
                    B.[NAME],
                    B.NAMEPY,
                    B.COMMENT,
                    B.POSTCODE,
                    B.PERSON,
                    B.TAXNo,
                    B.FAXno,
                    B.BANK,
                    B.Account,
                    B.ADDRESS,
                    b.Tel1,
                    b.tel2,
                    b.netaddress,
                    b.email,
                    b.CheckAndAccept,
                    b.BarterRate,
                    b.BarterTerm,
                    b.usertype,
                    b.branchid,
                    b.[Stop],
		    Case b.[stop] when 1 then '√' else ' ' end as StopMark,
                    --0 AS paridstop
                    ISNULL(( SELECT TOP 1
                                    [stop]
                             FROM   dbo.Btype
                             WHERE  typeid = @szTypeid
                           ), 0) AS paridstop,b.Person+' '+b.Tel2 as persona 
                           ,b.Personb+' '+b.Telb as personb
                           ,b.Personc+' '+b.Telc as personc,b.wuliu
            FROM    FN_GetPowerRangeBList(@OperatorID, @szTypeid,
                                          '1,2,3,4,6,7') B
            WHERE   ( ( @SearchFlag = 1
                        AND sonnum = 0
                        AND LEFT(typeid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND parid = @szTypeid
                         )
                    )
                    AND DELETED = 0
                    AND BranchID LIKE @BranchId + '%'
                    AND 
                    (
                    		BranchID like '00001%'
                    		OR
                    		(
                    			BranchID LIKE '00004%'
                    			AND
                    			BranchID IN ( SELECT BranchID FROM dbo.FN_GetPowerRangeBCList(@OperatorID  ,@BranchID ) )
                    		)
												OR
												(
													exists(select * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZCS')													
												)
                    )
                    AND ( fullname LIKE '%' + @szFullName + '%'
                          AND usercode LIKE '%' + @szUserCode + '%'
                        )
            ORDER BY CASE WHEN @con = 0 THEN TYPEID
                          ELSE usercode
                     END  


    IF @cMode = 'BC' 
        IF @SearchFlag = 0 
            SELECT  b.Branchid AS bCtypeid,
                    B.Branchid,
                    B.PARID,
                    B.SONNUM,
                    B.USERCODE,
                    B.FULLNAME,
                    B.[NAME],
                    B.NAMEPY,
                    B.COMMENT,
                    B.ADDRESS,
                    b.Tel,
                    b.email,
                    b.btypeid,
                    b.BranchType,
                    b.checkandaccept,
                    0 AS paridstop
            FROM    FN_GetPowerRangeBCTree(@OperatorID, @szTypeid) B
            WHERE   ( ( @SearchFlag = 1
                        AND sonnum = 0
                        AND LEFT(Branchid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND ( parid = @szTypeid )
                         )
                    )
                    AND DELETED = 0
                    AND ( fullname LIKE '%' + @szFullName + '%'
                          AND usercode LIKE '%' + @szUserCode + '%'
                        )
            ORDER BY CASE WHEN @con = 0 THEN Branchid
                          ELSE usercode
                     END  
        ELSE 
            SELECT  b.Branchid AS bCtypeid,
                    B.Branchid,
                    B.PARID,
                    B.SONNUM,
                    B.USERCODE,
                    B.FULLNAME,
                    B.[NAME],
                    B.NAMEPY,
                    B.COMMENT,
                    B.ADDRESS,
                    b.Tel,
                    b.email,
                    b.btypeid,
                    b.BranchType,
                    b.checkandaccept,
                    0 AS paridstop
            FROM    FN_GetPowerRangeBCList(@OperatorID, @szTypeid) B
            WHERE   ( ( @SearchFlag = 1
                        AND sonnum = 0
                        AND LEFT(Branchid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND ( parid = @szTypeid )
                         )
                    )
                    AND DELETED = 0
                    AND ( fullname LIKE '%' + @szFullName + '%'
                          AND usercode LIKE '%' + @szUserCode + '%'
                        )
            ORDER BY CASE WHEN @con = 0 THEN Branchid
                          ELSE usercode
                     END  

    IF @cMode = 'D' 
        SELECT  typeid AS dtypeid,
                TYPEID,
                PARID,
                SONNUM,
                USERCODE,
                FULLNAME,
                NAMEPY,
                COMMENT,
                branchid,
                0 AS paridstop
        FROM    DEPARTMENT
        WHERE   PARID = @szTypeid
                AND DELETED = 0
                AND BranchID LIKE @BranchId + '%'
                AND 
                (
                	BranchID = '00001'
                	OR
                	BranchID IN ( SELECT BranchID FROM dbo.FN_GetPowerRangeBCList( @OperatorID ,'') )	--qf 2011-11-16  加盟部门受权限控制
                )
        ORDER BY CASE WHEN @con = 0 THEN TYPEID
                          ELSE USERCODE
                     END  
    IF @cMode = 'E'
    --特殊说明下，职员选择时@szBarCode代表的职员所属的机构Id
        IF @SearchFlag = 0 
            SELECT  E.TYPEID,
                    E.TYPEID AS ETYPEID,
                    E.PARID,
                    E.SONNUM,
                    E.USERCODE,
                    E.FULLNAME,
                    E.[NAME],
                    E.NAMEPY,
                    E.COMMENT,
                    E.dtypeid,
                    ISNULL(D.FULLNAME, '') AS EDEPT,
                    E.TEL,
                    E.ADDRESS,
                    E.ZkPopedom,
                    E.YHPopedom,
                    E.isShopSale,
                    E.branchid,
                    E.Branchid AS bCtypeid,
                    E.[Stop],
		    Case E.[stop] when 1 then '√' else ' ' end as StopMark,
                    ISNULL(( SELECT TOP 1
                                    [stop]
                             FROM   dbo.Employee
                             WHERE  typeid = @szTypeid
                           ), 0) AS paridstop
                    --0 AS paridstop
            FROM    FN_GetPowerRangeETree(@OperatorID, @szTypeid) E
                    LEFT OUTER JOIN DEPARTMENT D ON E.dtypeid = D.TYPEID
            WHERE   ( ( @SearchFlag = 1
                        AND e.sonnum = 0
                        AND LEFT(e.typeid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND e.parid = case when @szTypeid='00000' then '0' when @szTypeid='' then '00000' else @szTypeid end
                         )
                    )
                    AND e.DELETED = 0 
				--and e.BranchId=case when @szBarCode='' then e.BranchId else @szBarCode end
                    AND e.branchID LIKE @BranchId + '%'
                    AND 
                    (
                    		e.BranchID like '00001%'
                    		OR
                    		(
                    			e.BranchID LIKE '00004%'
                    			AND
                    			e.BranchID IN ( SELECT BranchID FROM dbo.FN_GetPowerRangeBCList(@OperatorID  ,@BranchID ) )
                    		)
                    )
                    AND ( e.fullname LIKE '%' + @szFullName + '%'
                          AND e.usercode LIKE '%' + @szUserCode + '%'
                        )
            ORDER BY CASE WHEN @con = 0 THEN e.TYPEID
                          ELSE e.usercode
                     END  
        ELSE 
            SELECT  E.TYPEID,
                    E.TYPEID AS ETYPEID,
                    E.PARID,
                    E.SONNUM,
                    E.USERCODE,
                    E.FULLNAME,
                    E.[NAME],
                    E.NAMEPY,
                    E.COMMENT,
                    E.dtypeid,
                    ISNULL(D.FULLNAME, '') AS EDEPT,
                    E.TEL,
                    E.ADDRESS,
                    E.ZkPopedom,
                    E.YHPopedom,
                    E.isShopSale,
                    E.branchid,
                    E.Branchid AS bCtypeid,
                    E.[Stop],
		    Case E.[stop] when 1 then '√' else ' ' end as StopMark,
                    ISNULL(( SELECT TOP 1
                                    [stop]
                             FROM   dbo.Employee
                             WHERE  typeid = @szTypeid
                           ), 0) AS paridstop
                    --0 AS paridstop
            FROM    FN_GetPowerRangeEList(@OperatorID, @szTypeid) E
                    LEFT OUTER JOIN DEPARTMENT D ON E.dtypeid = D.TYPEID
            WHERE   ( ( @SearchFlag = 1
                        AND e.sonnum = 0
                        AND e.typeid <> '00000'
                        AND LEFT(e.typeid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND e.parid = @szTypeid
                         )
                    )
                    AND e.DELETED = 0 
				--and e.BranchId=case when @szBarCode='' then e.BranchId else @szBarCode end
                    AND e.branchID LIKE @BranchId + '%'
                    AND 
                    (
                    		e.BranchID like '00001%'
                    		OR
                    		(
                    			e.BranchID LIKE '00004%'
                    			AND
                    			e.BranchID IN ( SELECT BranchID FROM dbo.FN_GetPowerRangeBCList(@OperatorID  ,@BranchID ) )
                    		)
                    )
                    AND ( e.fullname LIKE '%' + @szFullName + '%'
                          AND e.usercode LIKE '%' + @szUserCode + '%'
                        )
            ORDER BY CASE WHEN @con = 0 THEN e.TYPEID
                          ELSE e.usercode
                     END  
	  
	  
    IF @cMode = 'K' 
        BEGIN
            IF @BranchId = '00000' 
                SET @BranchId = ''
            IF @szTypeid = '' 
                SELECT  TYPEID,
                        TYPEID AS Ktypeid,
                        PARID,
                        SONNUM,
                        USERCODE,
                        FULLNAME,
                        [NAME],
                        NAMEPY,
                        COMMENT,
                        Branchid,
												BranchId as BCTypeId,
                        branchType,
                        0 AS paridstop,
                        isdefault,
                        CASE WHEN isdefault = 1 THEN '√'
                             ELSE ''
                        END AS dkfullname
                FROM    stock p
                WHERE   ( ( @SearchFlag = 1
                            AND sonnum = 0
                          )
                          OR (@SearchFlag = 0 and parid not in (select typeid from stock where sonnum > 0 and [leveal] > 0))
                        )
                        AND typeid <> '99999'
                        AND typeid <> '00000'
                        AND EXISTS (
                        SELECT  1
                        FROM   dbo.FN_GetStockListOfBranchIni(@OperatorID,@branchid,'') slb WHERE slb.KtypeId like p.TypeID + '%' )
                        AND DELETED = 0 and BranchId in (Select BranchID from Branch where sonnum = 0 and Deleted = 0)
                        AND ( p.fullname LIKE '%' + @szFullName + '%'
                              AND usercode LIKE '%' + @szUserCode + '%'
                            )  --and len(typeid) > 5 
                ORDER BY CASE WHEN @con = 0 THEN BranchId
                              ELSE usercode
                         END,
                        usercode
            ELSE 
                SELECT  TYPEID,
                        TYPEID AS Ktypeid,
                        PARID,
                        SONNUM,
                        USERCODE,
                        FULLNAME,
                        [NAME],
                        NAMEPY,
                        COMMENT,
                        Branchid,
												BranchId as bctypeId,
                        branchType,
                        isdefault,
                        CASE WHEN isdefault = 1 THEN '√'
                             ELSE ''
                        END AS dkfullname
                FROM    stock p
                WHERE   ( ( @SearchFlag = 1
                            AND sonnum = 0
                          )
                          OR (@SearchFlag <> 1
													AND (exists(select * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZBS') or ((@szTypeid = '00000' and
												    parid not in (select typeid from stock where sonnum > 0 and [leveal] > 0)))
													  or (@szTypeid <> '00000' and parid = @szTypeid )))
                        )
												AND (exists(select * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZCS') or p.parid = @szTypeid)
--@szTypeid=case @szTypeid when '00001' then p.parid else left(p.parid, len(@szTypeid)) end
                        AND typeid <> '99999'
                        AND typeid <> '00000' and BranchId in (Select BranchID from Branch where sonnum = 0 and Deleted = 0)
                        AND EXISTS (
                        SELECT  1
                        FROM   dbo.FN_GetStockListOfBranchIni(@OperatorID,@branchid,'') slb WHERE slb.KtypeId like p.TypeID + '%')
                        AND DELETED = 0
                        AND ( p.fullname LIKE '%' + @szFullName + '%'
                              AND usercode LIKE '%' + @szUserCode + '%'
                            ) -- and len(typeid) > 5 
                ORDER BY CASE WHEN @con = 0 THEN BranchId
                              ELSE usercode
                         END,
                        usercode

        END
    IF @cMode = 'P' 
        IF @SearchFlag = 0 
            SELECT  TYPEID,
                    typeid AS ptypeid,
                    PARID,
                    SONNUM,
                    p.USERCODE,
                    FULLNAME,
                    p.NAME,
                    NAMEPY,
                    p.COMMENT,
                    STANDARD,
                    TYPE,
                    AREA,
                    UNIT1,
                    UNIT2,
                    UNITRATE1,
                    CASE COSTMODE
                      WHEN 0 THEN '加权平均法'
                      WHEN 1 THEN '先进先出法'
                      WHEN 2 THEN '后进先出法'
                      WHEN 3 THEN '手工指定法'
                    END AS Costmode,
                    BARCODE,
                    Stop,
		    Case [stop] when 1 then '√' else ' ' end as StopMark,
                    retailPrice,
                    bar.PlanDetail AS formatid,
                    CSPZ,
                    trade,
                    IssueDate,
                    BREAKWARN,
                    ISNULL(( SELECT TOP 1
                                    stop
                             FROM   ptype
                             WHERE  typeid = @szTypeid
                           ), 0) AS paridstop,
                    ChangeRule
            FROM    FN_GetPowerRangePTree(@OperatorID, @szTypeid) P,
                    dbo.BarCodePlan bar
            WHERE   ( ( @SearchFlag = 1
                        AND sonnum = 0
                        AND LEFT(typeid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND parid = @szTypeid
                         )
                    )
                    AND p.FormatID = CAST(bar.PlanId AS VARCHAR)
                    AND DELETED = 0
                    AND typeid <> '00000'
                    AND ( p.fullname LIKE '%' + @szFullName + '%'
                          AND p.usercode LIKE '%' + @szUserCode + '%'
                          AND p.StopDate LIKE @szStopDate + '%'
                          AND p.BarCode LIKE '%' + @szBarCode + '%'
                          AND p.name LIKE '%' + @szName + '%'
                          AND p.IssueDate LIKE @szIssueDate + '%'
                        )
            ORDER BY CASE WHEN @con = 1 THEN p.usercode
                          ELSE RIGHT('0000000000' + CAST(p.porder AS VARCHAR),
                                     10)
                     END,
                    typeid  
  
        ELSE 
            SELECT  TYPEID,
                    typeid AS ptypeid,
                    PARID,
                    SONNUM,
                    p.USERCODE,
                    FULLNAME,
                    p.NAME,
                    NAMEPY,
                    p.COMMENT,
                    STANDARD,
                    TYPE,
                    AREA,
                    UNIT1,
                    UNIT2,
                    UNITRATE1,
                    CASE COSTMODE
                      WHEN 0 THEN '加权平均法'
                      WHEN 1 THEN '先进先出法'
                      WHEN 2 THEN '后进先出法'
                      WHEN 3 THEN '手工指定法'
                    END AS Costmode,
                    BARCODE,
                    Stop,
		    Case [stop] when 1 then '√' else ' ' end as StopMark,
                    retailPrice,
                    bar.PlanDetail AS formatid,
                    CSPZ,
                    trade,
                    IssueDate,
                    BREAKWARN,
                    0 AS paridstop,
                    ChangeRule
            FROM    FN_GetPowerRangePList(@OperatorID, @szTypeid) P,
                    dbo.BarCodePlan bar
            WHERE   ( ( @SearchFlag = 1
                        AND sonnum = 0
                        AND LEFT(typeid, LEN(@szTypeid)) = @szTypeid
                      )
                      OR ( @SearchFlag = 0
                           AND parid = @szTypeid
                         )
                    )
                    AND p.FormatID = CAST(bar.PlanId AS VARCHAR)
                    AND DELETED = 0
                    AND typeid <> '00000'
                    AND ( p.fullname LIKE '%' + @szFullName + '%'
                          AND p.usercode LIKE '%' + @szUserCode + '%'
                          AND p.StopDate LIKE @szStopDate + '%'
                          AND p.BarCode LIKE '%' + @szBarCode + '%'
                          AND p.name LIKE '%' + @szName + '%'
                          AND p.IssueDate LIKE @szIssueDate + '%'
                        )
            ORDER BY CASE WHEN @con = 1 THEN p.usercode
                          ELSE RIGHT('0000000000' + CAST(p.porder AS VARCHAR),
                                     10)
                     END,
                    typeid  

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/******************************************20130722********************************************/
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZInfoDelete]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZInfoDelete]
GO





--  ********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：F_B_InfoDelete                                                   
--  ||   过程功能：删除基本信息（包括，会计科目、往来单位、职员、仓库、部门、商品）  
--  ||=========================================================================================  
--  ||   参数说明：  参数名称         类型            意义                     输入输出  
--  ||            -----------------------------------------------------------------------------  
--  ||   @TypeId   varchar(50),                    --ID  
--  ||   @DbName  varchar(50)  要删除的数据库表名  
--  ||=========================================================================================     
--  ||   过程历史：  操作         作者         日期          描述  
--  ||            -----------------------------------------------------------------------------  
--  ||              ALTER        broch        2004.04.10   first ALTER                                                      
--  ||              modify       broch        2004.04.10   first modify                                                     
--  ********************************************************************************************  
/*
作者：cqhua
日期：2011-08-19
修改原因：合并BS、CS。其间删除时，要判断产品版本，不同版本删除控制不一样.如机构、仓库
*/

CREATE     PROCEDURE FZInfoDelete
    (
      @typeid VARCHAR(50),
      @dbname VARCHAR(50),
      @branchid VARCHAR(50) = '0000100001'  
    )
AS 
    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 @szName VARCHAR(50)  
    DECLARE @Ktypeid VARCHAR(50)
    DECLARE @Btypeid VARCHAR(50)
    DECLARE @UpdateTag INT
    DECLARE @leveal SMALLINT  
    DECLARE @cgId INT  --颜色组编号  
    DECLARE @nRst INT  
    SELECT  @szName = 'iniover'                  

	IF EXISTS(SELECT SubValue FROM sysdata WHERE SubName = 'ProcTypeName' AND Subvalue='FZCS')
	    EXEC @nRst = FZCheckBaseIsUsed_CS @typeid, @dbname, @branchid  
	ELSE
	    EXEC @nRst = FZCheckBaseIsUsed_BS @typeid, @dbname, @branchid  
    IF @nRst < 0 
        RETURN @nRst   
 
    DECLARE @ProcType VARCHAR(50)  
    SELECT  @ProcType = subvalue
    FROM    sysdata
    WHERE   subName = 'ProcTypeName'   
	
	if @dbname = 'Branch'
	begin
		exec('select top 1 1 from '+@dbname+' where branchid='''+@typeid+''' and deleted =1')
		if @@rowcount =1 return 0
	end
	else IF @dbname = 'atype'
	begin
		IF LEFT(@branchid,5)='00001'
			exec('select top 1 1 from '+@dbname+' where LEFT(branchid,5)=''00001''  and typeid='''+@typeid+''' and deleted =1')
		ELSE
			exec('select top 1 1 from '+@dbname+' where branchid='''+@branchid+'''  and typeid='''+@typeid+''' and deleted =1')		
		if @@rowcount =1 return 0
	end
	ELSE 
	begin
		exec('select top 1 1 from '+@dbname+' where typeid='''+@typeid+''' and deleted =1')
		if @@rowcount =1 return 0
	end
    IF @dbname = 'atype' 
        GOTO DelAtype  
    IF @dbname = 'btype' 
        GOTO DelBtype  
    IF @dbname = 'department' 
        GOTO DelDepartment  
    IF @dbname = 'employee' 
        GOTO DelEmployee  
    IF @dbname = 'stock' 
        GOTO DelStock  
    IF @dbname = 'ptype' 
        GOTO DelPtype  
    IF @dbname = 'ZONE' 
        GOTO DelZone  

    IF @dbname = 'Branch' 
        GOTO Delbranch
    IF @dbname = 'AREA' 
        GOTO DELArea  
  




 --if @dbname='areatype' Goto DelAreaType  
 --if @dbname='zerotype'   Goto DelZeroType            
-- 检查ATYPE是否能够删除  
    DelAtype:  
    EXEC [dbo].[XW_GetUpdateTag] 'Atype', @UpdateTag OUTPUT
    
    IF EXISTS(SELECT 1 FROM dbo.DZTConfig WHERE AtypeZFB = @typeid OR AtypeTFSR = @typeid OR AtypeYFZC = @typeid OR AtypeSCKF = @typeid)
    RETURN -160

    IF EXISTS(SELECT 1 FROM dbo.tpx_PosCashTypeConfig WHERE Atypeid = @typeid)
    RETURN -174
    
    IF EXISTS(SELECT 1 FROM dbo.Branch WHERE Deleted=0 AND PayAtypeId = @typeid)
    RETURN -181 
    
    IF @branchid = ''
        OR LEFT(@branchid, 5) = '00001' --总部机构
        SET @branchid = '0000100001'
    IF @branchid = '0000100001' 
        BEGIN
            UPDATE  atype
            SET     [deleted] = 1,
                    UpdateTag = @UpdateTag
            WHERE   (@procType = 'FZCS' or LEFT(branchid, 5) = '00001')
                    AND [typeid] = @typeid    
            IF @@ROWCOUNT = 0 
                GOTO error106  
            ELSE 
                BEGIN   
                    SELECT  @parid = [parid]
                    FROM    atype
                    WHERE   branchid = @branchid
                            AND [typeid] = @typeid   
                    SELECT  @sonnum = [sonnum]
                    FROM    atype
                    WHERE   branchid = @branchid
                            AND [typeid] = @parid  
                    UPDATE  atype
                    SET     [sonnum] = @sonnum - 1,
                            UpdateTag = @UpdateTag
                    WHERE   (@procType = 'FZCS' or LEFT(branchid, 5) = '00001')
                            AND [typeid] = @parid   
                    RETURN 0  
                END  
        END
    ELSE  -- 加盟机构
        BEGIN
            UPDATE  atype
            SET     [deleted] = 1,
                    UpdateTag = @UpdateTag
            WHERE   branchid = @branchid
                    AND [typeid] = @typeid    
            IF @@ROWCOUNT = 0 
                GOTO error106  
            ELSE 
                BEGIN   
                    SELECT  @parid = [parid]
                    FROM    atype
                    WHERE   branchid = @branchid
                            AND [typeid] = @typeid   
                    SELECT  @sonnum = [sonnum]
                    FROM    atype
                    WHERE   branchid = @branchid
                            AND [typeid] = @parid  
                    UPDATE  atype
                    SET     [sonnum] = @sonnum - 1,
                            UpdateTag = @UpdateTag
                    WHERE   branchid = @branchid
                            AND [typeid] = @parid   
                    RETURN 0  
                END  
        END
-- 检查PTYPE是否能够删除  
    DelPtype:  
    IF EXISTS(SELECT 1 FROM tpx_CXSpecialPtype WHERE PtypeId = @typeid) RETURN -8
    IF EXISTS(SELECT 1 FROM tpx_PtypeSaleRight WHERE PtypeId = @typeid) RETURN -8
    BEGIN TRAN DDPtype
    EXEC [dbo].[XW_GetUpdateTag] 'ptype', @UpdateTag OUTPUT
    DECLARE @formatid VARCHAR(10)  
    UPDATE  ptype
    SET     [deleted] = 1,
            UpdateTag = @UpdateTag
    WHERE   [typeid] = @typeid   
    IF @@rowcount = 0 
    BEGIN
        ROLLBACK TRAN DDPtype
        RETURN -100   
	END        
    ELSE 
        BEGIN   
            SELECT  @parid = [parid]
            FROM    ptype
            WHERE   [typeid] = @typeid  
            SELECT  @sonnum = [sonnum],
                    @formatid = formatid
            FROM    ptype
            WHERE   [typeid] = @parid   
            UPDATE  ptype
            SET     [sonnum] = @sonnum - 1,
                    UpdateTag = @UpdateTag
            WHERE   [typeid] = @parid  
            DELETE  ptypecolor
            WHERE   ptypeid = @typeid
            DELETE  ptypesize
            WHERE   ptypeid = @typeid
            DELETE  FROM ptypebar
            WHERE   ptypeid = @typeid  
  
            DELETE  PtypeAttribute
            WHERE   PtypeId = @typeid --2011年7月22日14:22:49 黃文武 
			delete from PriceModifyHis where PtypeId = @typeid --删除商品价格修改记录

            DELETE  FROM SalabilityPtype
            WHERE   ptypeid = @typeid  --商品组  
            declare @re int
            IF ( SELECT MAX(Sonnum) FROM   Ptype WHERE  Typeid = @parid) = 0 
            BEGIN  
             --处理条码  
             EXEC @re=PtypeBarForParent @ptypeid1 = @parid
             if @re<>0
             BEGIN
				ROLLBACK TRAN DDPtype
				RETURN -100 
			  END
            END  
            commit TRAN  DDPtype
            RETURN 0  
        END  
-- 检查BTYPE是否能够删除  
    DelBtype:  
    EXEC [dbo].[XW_GetUpdateTag] 'btype', @UpdateTag OUTPUT
    
    IF EXISTS(SELECT 1 FROM dbo.DZTConfig WHERE BTypeJZ = @typeid OR BtypeSC = @typeid OR BtypeYF = @typeid)
    	RETURN -160
    
    SELECT  @parid = [parid],
            @sonnum = [sonnum]
    FROM    btype
    WHERE   [typeid] = @typeid   

    IF @procType = 'FZCS'
        AND @typeid IN ( '00001', '00002', '00006', '00005', '00003',
                         '0000100001', '0000200001', '0000600001',
                         '0000500001', '0000300001' ) 
        RETURN -1    
    IF @procType <> 'FZCS'
        AND @typeid IN ( '00000', '00001', '0000100001', '00002', '0000200001',
                         '00003', '0000300001', '00004', '00006', '00007',
                         '0000700001' ) 
        RETURN -11  

    UPDATE  btype
    SET     [deleted] = 1,
            updatetag = @UpdateTag
    WHERE   [typeid] = @typeid  
    IF @@rowcount = 0 
        RETURN -1   
    ELSE 
        BEGIN   
            SELECT  @parid = [parid]
            FROM    btype
            WHERE   [typeid] = @typeid   
            SELECT  @sonnum = [sonnum]
            FROM    btype
            WHERE   [typeid] = @parid  
            UPDATE  btype
            SET     [sonnum] = @sonnum - 1,
                    updatetag = @UpdateTag
            WHERE   [typeid] = @parid   
			delete from ChangeGoodsSetting where btypeid =@typeid
  --  if left(@typeid,5)in('00003','00007') Goto DelStock  
            RETURN 0  

        END      
   
-- 检查branch是否能够删除  

 
Delbranch: 
   
 EXEC [dbo].[XW_GetUpdateTag] 'Branch', @UpdateTag OUTPUT
 Select @parid=[parid], @sonnum=[sonnum]   From branch  Where [branchid]=@typeid   
 
 --零售计划相关使用过机构
 IF EXISTS(SELECT 1 FROM SalePlanBillDetail WHERE BranchID = @typeid) RETURN -170
 --机构在VIP卡中被使用
 IF EXISTS(SELECT 1 FROM dbo.VipCards WHERE HandOutDept = @typeid) RETURN -171
 --机构在店账通中使用
 IF EXISTS(SELECT 1 FROM dbo.DZTConfig WHERE Branchid = @typeid) RETURN -172
 --机构在POS店铺分组管理中使用
 IF EXISTS(SELECT 1 FROM dbo.tpx_StorePackS WHERE jtypeid = @typeid) RETURN -173
 IF EXISTS(SELECT 1 FROM tpx_CheckPointNdx WHERE Jtypeid = @typeid) RETURN -8
 IF EXISTS(SELECT 1 FROM tpx_CXSpecialPtype WHERE Jtypeid = @typeid) RETURN -8
     
 if @procType <> 'FZCS' AND @typeid in('00001','0000100001','00004')  
    return -11 
 ELSE IF  @procType = 'FZCS' AND @typeid IN ( '00001', '0000100001' ) 
 	RETURN -1 
 else  
 Begin   
   begin tran
--select * from stock where branchid=@typeid
   if exists(select 1 from stock where branchid=@typeid) 
   begin

      set @Ktypeid = ''
      while exists(select top 1 typeid from stock where sonnum=0 and branchid=@typeid and typeid > @Ktypeid order by typeid)
      begin
        select top 1 @Ktypeid =  typeid from stock where sonnum=0 and  branchid=@typeid and typeid > @Ktypeid order by typeid
        --print 'TA'+@Ktypeid 
        exec @nRst = FZInfoDelete @Ktypeid,'stock'  
        if @nRst < 0  AND @nRst<>-201  -- -201 表示删除已删除的基本信息
        begin
         -- print 'TC'+@Ktypeid
			--return @nRst  
           --print @nrst
          rollback tran 
          goto errorBranchStock
        end
     end
	 set @Ktypeid = ''
	 declare kcursor Cursor for select  typeid from stock where branchid=@typeid AND DELETED =0 order by leveal desc
	 open 	kcursor
	 FETCH NEXT FROM kcursor into @Ktypeid
     while @@FETCH_STATUS =0
     begin
        exec @nRst = FZInfoDelete @Ktypeid,'stock'  
		--print 'TB'+@Ktypeid
        if @nRst < 0  AND @nRst<>-201  -- -201 表示删除已删除的基本信息
        begin
			CLOSE Kcursor  
            DEALLOCATE Kcursor 
          --return @nRst  
          -- print 'TD'+@Ktypeid
			--select  * from stock where branchid=@typeid
          rollback tran 
          goto errorBranchStock
        end
        FETCH NEXT FROM kcursor into @Ktypeid
     end
	 close kcursor
	 DEALLOCATE kcursor
   end
   if exists(select 1 from branch where branchid = @typeid and ( BranchType = 4 OR branchType=7)) -- 删除加盟对应总部的应收单位 及 总部对加盟的应付单位
   begin
     select @btypeid = Btypeid from branch where branchid=@typeid 
     exec @nRst = FZInfoDelete @btypeid,'Btype'  
     if @nRst < 0  AND @nRst<>-201  -- -201 表示删除已删除的基本信息
     begin
       --return @nRst  
       --print @nrst
       rollback tran 
       goto errorBranchBtype
     end     
   end 
   Update branch set [deleted]=1,updatetag = @UpdateTag Where [branchid]=@typeid  
   if @@rowcount=0  begin
    rollback tran
    Return -1   
   end
   else   
   begin   
    Select @parid=[parid]  From branch  Where [branchid]=@typeid   
    Select @sonnum=[sonnum] From branch  Where [branchid]=@parid  
    Update branch set [sonnum]= @sonnum-1,updatetag = @UpdateTag  Where [branchid] =@parid   
	DELETE FROM Atype WHERE branchid=@typeid -- 删除相关机构会计科目
	if 	 EXISTS(SELECT SubValue FROM sysdata WHERE SubName = 'ProcTypeName' AND Subvalue<>'FZCS') AND exists(select 1 from branch where branchid = @typeid and ( BranchType = 4 ))  --删除加盟机构，直接删除所属基本信息,及更新相应Sonnum,soncount,UpdateTag
	BEGIN
		delete from btype where branchid =@typeid
		delete from employee where branchid =@typeid
		delete from DepartMent where branchid =@typeid

	 	EXEC [dbo].[XW_GetUpdateTag] 'btype', @UpdateTag OUTPUT		
	    UPDATE  btype
	    SET     updatetag = @updateTag,
	            SonNum = ISNULL(( SELECT    COUNT(Typeid)
	                              FROM      btype
	                              WHERE     a.typeid = Parid
	                                        --AND deleted = 0
	                            ), 0)
	    FROM    btype a
	
	    UPDATE  btype
	    SET     updatetag = @updateTag,
	            SonCount = ISNULL(( SELECT  CAST(MAX(RIGHT(typeid, 5)) AS INT)
	                                FROM    btype
	                                WHERE   a.typeid = Parid
	                                        --AND deleted = 0
	                              ), 0)
	    FROM    btype a
		
		EXEC [dbo].[XW_GetUpdateTag] 'employee', @UpdateTag OUTPUT	
	    UPDATE  employee
	    SET     updatetag = @updateTag,
	            SonNum = ISNULL(( SELECT    COUNT(Typeid)
	                              FROM      employee
	                              WHERE     a.typeid = Parid
	                                        --AND deleted = 0
	                            ), 0)
	    FROM    employee a
	
	    UPDATE  employee
	    SET     updatetag = @updateTag,
	            SonCount = ISNULL(( SELECT  CAST(MAX(RIGHT(typeid, 5)) AS INT)
	                                FROM    employee
	                                WHERE   a.typeid = Parid
	                                        --AND deleted = 0
	                              ), 0)
	    FROM    employee a
	
	    EXEC [dbo].[XW_GetUpdateTag] 'department', @UpdateTag OUTPUT	
	    UPDATE  department
	    SET     updatetag = @updateTag,
	            SonNum = ISNULL(( SELECT    COUNT(Typeid)
	                              FROM      department
	                              WHERE     a.typeid = Parid
	                                        --AND deleted = 0
	                            ), 0)
	    FROM    department a
	
	    UPDATE  department
	    SET     updatetag = @updateTag,
	            SonCount = ISNULL(( SELECT  CAST(MAX(RIGHT(typeid, 5)) AS INT)
	                                FROM    department
	                                WHERE   a.typeid = Parid
	                                        --AND deleted = 0
	                              ), 0)
	    FROM    department a

	END
	delete from OperationInfo where  branchid =@typeid
    commit tran
    Return 0  
   end  
 End      
    
 
-- 检查EMPLOYEE是否能够删除  
    DelEmployee: 
    EXEC [dbo].[XW_GetUpdateTag] 'employee', @UpdateTag OUTPUT     
    
    --零售计划相关使用过职员
	IF EXISTS(SELECT 1 FROM SalePlanConfig WHERE EtypeID = @typeid) RETURN -170
	IF EXISTS(SELECT 1 FROM SalePlanBill WHERE MakeBillEtypeID = @typeid OR MakeEtypeID = @typeid OR AduitEtypeID = @typeid OR EndEtypeID = @typeid) RETURN -170
	IF EXISTS(SELECT 1 FROM SalePlanBillDetail WHERE EtypeID = @typeid) RETURN -170
	-- 职员被设置为POS人员
	IF EXISTS(SELECT 1 FROM dbo.tpx_PosEtype WHERE Typeid = @typeid) RETURN -175
	IF EXISTS(SELECT 1 FROM dbo.tpx_PtypeSaleRight WHERE EtypeId = @typeid) RETURN -8
	
    UPDATE  employee
    SET     [deleted] = 1,
            updatetag = @UpdateTag
    WHERE   [typeid] = @typeid   
    IF @@rowcount = 0 
        RETURN -1   
    ELSE 
        BEGIN   
            SELECT  @parid = [parid]
            FROM    employee
            WHERE   [typeid] = @typeid   
            SELECT  @sonnum = [sonnum]
            FROM    employee
            WHERE   [typeid] = @parid  
            UPDATE  employee
            SET     [sonnum] = @sonnum - 1,
                    updatetag = @UpdateTag
            WHERE   [typeid] = @parid   
            DELETE  employeepower
            WHERE   etypeid = @typeid  
            RETURN 0  
        END  
-- 检查STOCK是否能够删除  
    DelStock: 
    
    IF EXISTS(SELECT 1 FROM tpx_CheckPointNdx WHERE KtypeID = @typeid)
    RETURN -8
    EXEC [dbo].[XW_GetUpdateTag] 'stock', @UpdateTag OUTPUT 
    SELECT  @parid = [parid]
    FROM    stock
    WHERE   [typeid] = @typeid   
    IF @procType = 'FZBS'
        AND @typeid IN ( '00000' ) 
        RETURN -1  
    IF @procType = 'FZCS'
        AND @typeid IN ( '00001', '00007', '00003', '00004', '0000100001' ) 
        RETURN -1    


    UPDATE  stock
    SET     [deleted] = 1,
            updatetag = @UpdateTag
    WHERE   [typeid] = @typeid   
    IF @@rowcount = 0 
        RETURN -1   
    ELSE 
        BEGIN   
            SELECT  @parid = [parid]
            FROM    stock
            WHERE   [typeid] = @typeid   
            SELECT  @sonnum = [sonnum]
            FROM    stock
            WHERE   [typeid] = @parid  
            UPDATE  stock
            SET     [sonnum] = @sonnum - 1,
                    updatetag = @UpdateTag
            WHERE   [typeid] = @parid   
	
	--设置默认仓库(删除时）
            EXEC SetDefaultStock @typeid, 2

--     if left(@typeid,5)in('00003','00007')   
--     Begin  
--      if exists(select * from btype where typeid = @typeid and deleted = 0)  
--      begin  
--       Update btype set [deleted]=1 Where [typeid]=@typeid  
--       if @@rowcount=0  Return -1   
--       else   
--       Begin  
--             Select @parid=[parid]   From btype  Where [typeid]=@typeid   
--        Select @sonnum=[sonnum] From btype  Where [typeid]=@parid  
--        Update btype set [sonnum]=@sonnum-1  Where [typeid]=@parid   
--        delete from stocksysdata where [stypeid] = @typeid  
--        if @@rowcount=0  Return -1   
--       End   
--      end  
--     End  
            RETURN 0  

        END  
-- 检查Depatment是否能够删除  
    DelDepartment:  
    EXEC [dbo].[XW_GetUpdateTag] 'Department', @UpdateTag OUTPUT 
    UPDATE  Department
    SET     [deleted] = 1,
            updatetag = @UpdateTag
    WHERE   [typeid] = @typeid  
    IF @@rowcount = 0 
        RETURN -1   
    ELSE 
        BEGIN   
            SELECT  @parid = [parid]
            FROM    department
            WHERE   [typeid] = @typeid   
            SELECT  @sonnum = [sonnum]
            FROM    department
            WHERE   [typeid] = @parid  
            UPDATE  department
            SET     [sonnum] = @sonnum - 1,
                    updatetag = @UpdateTag
            WHERE   [typeid] = @parid   
            RETURN 0  
        END  
    DELZone:   
    BEGIN  
        SELECT  @parid = ParID
        FROM    Zone
        WHERE   ZoneiD = @typeid  
        BEGIN TRAN insertproc  
        UPDATE  Zone
        SET     Deleted = 1
        WHERE   ZoneID = @Typeid  
        IF NOT EXISTS ( SELECT  ZoneID
                        FROM    Zone
                        WHERE   ParID = @parid
                                AND deleted = 0 ) 
            UPDATE  Zone
            SET     isClass = 0
            WHERE   ZoneID = @parid  
        IF @@error <> 0 
            GOTO error108  
        ELSE 
            COMMIT TRAN insertproc  
        GOTO success  
    END  
    DELArea:   
    BEGIN  
        BEGIN TRAN insertproc  
        DELETE  Area
        WHERE   AreaID = @Typeid  
        IF @@error <> 0 
            GOTO error106  
        ELSE 
            COMMIT TRAN insertproc  
        GOTO success  
    END  
    success:
    RETURN 0  
    error101:
    RETURN -1                 -- 数据库操作失败，请稍后重试！  
    error102:
    RETURN -2                  -- 此记录已经过账，不能再分类！  
    error103:
    RETURN -3                  -- 父亲ID号不存在！  
    error104:
    RETURN -4                  -- 系统行不允许修改！  
    error105:
    RETURN -5                  -- '该记录的编号或全名与其它记录相同，与你的配置不符！'+char(13)+  
     --          '请更改记录或在基本信息设置模块更改配置！'   
    error107:
    RETURN -7                  --该记录有下级记录，故不能删除！  
    error106:   
    ROLLBACK TRAN insertproc   
    RETURN -1    -- 数据库操作失败，请稍后重试！  
    error108:  
    BEGIN  
        IF @@TRANCOUNT > 0 
            ROLLBACK TRAN   
        RETURN -8                --该记录已经被使用   
    END  
    errorBranchStock:
    RETURN -9                 -- 有下级仓库不能删除机构
    errorBranchBtype:
    RETURN -10
                 -- 加盟客户使用过不能删除机构






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/******************************************20130722********************************************/
/******************************************20130725********************************************/
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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



Create  PROCEDURE FZOnePtypeAnalyse_BS  
(  
	 @PtypeID 	varchar(50),  
	 @Period  	int,  
	 @year    	varchar(5),
	 @branchid      varchar(2000),   
	 @OperatorId	varchar(50)    
)AS  
 Set nocount on  

Declare @TempPtypeID varchar(50)
SET @TempPtypeID=@PtypeID
  
Declare @OperatorIsJM bit
select @OperatorIsJM = SelfHelp from Branch a Left join Employee b on a.branchid = b.branchid where b.typeid = @OperatorId

if ((@PtypeID='' )or (@PtypeID='00000'))  Select @PtypeID='%'  
  
 Declare @StartDate VARCHAR(10), @EndDate VARCHAR(10),@sonnum int

 Set @Year=LEFT(@Year,4)
   
--    先建立临时表，然后装入数据12个月加一年的合计数据  
  
 if object_id('tempdb..#tempOnePtype') is not null drop table #tempOnePtype  
      SELECT IDENTITY(int, 1,1) as IDEID,ptypeid,qty, DiscountTotal , costTotal into #tempOnePtype  
 from DlyData where 1<>1  
 
 if object_id('tempdb..#Ptype_tmp') is not null drop table #Ptype_tmp  
 select TypeID INTO #Ptype_tmp from FN_GetPowerRangePList(@OperatorId,@TempPtypeID)
 if object_id('tempdb..#Btype_tmp') is not null drop table #Btype_tmp 
 select TypeId INTO #Btype_tmp from FN_GetPowerRangeBList(@OperatorId,'','2,3,4,6') 
 if object_id('tempdb..#Etype_tmp') is not null drop table #Etype_tmp
 select TypeId INTO #Etype_tmp from FN_GetPowerRangeEList(@OperatorId,'')
 if object_id('tempdb..#Ktype_tmp') is not null drop table #Ktype_tmp
 select KtypeId,SelfHelp INTO #Ktype_tmp from FN_GetStockListOfBranch(@OperatorID,@BranchId,'')
 if object_id('tempdb..#vchtype_tmp') is not null drop table #vchtype_tmp  
 select Vchtype INTO #vchtype_tmp from FN_GetPowerRangeVList(@BranchId)
 
  
 --写入每个月的数据  
if @Period<>13  
begin  
 SET IDENTITY_INSERT #tempOnePtype  on   
   
 INSERT INTO #tempOnePtype (IDEID,ptypeid,qty,DisCountTotal,CostTotal)    
 Select CAST(right(date,2) as int),ptypeid,qty,discountTotal,CostTotal from 
(  
	 SELECT left(dd.date,7) as date ,'' [ptypeid],-SUM([qty]) AS [Qty],  
	   -SUM([BargainTotal]) AS [discountTotal],-Sum(CostTotal) as CostTotal  
	   FROM DlyData dd  
	WHERE billtype=2 AND left(date,4)=@Year  
	and usedtype =case when vchtype in(222,224) then 1 else usedtype end  
	and exists(select 1  from #Ptype_tmp FilterP  where dd.PtypeId = FilterP.TypeId)  
	and exists(select 1  from #Btype_tmp FilterB  where dd.BtypeId = FilterB.TypeId)  
	and exists(select 1  from #Etype_tmp FilterE  where dd.EtypeId = FilterE.TypeId)  
	and exists(select 1  from #Ktype_tmp FilterK where dd.ktypeId = Filterk.KtypeId and selfhelp = @OperatorIsJM)     
	and exists(select 1  from #vchtype_tmp FilterV where dd.vchtype=FilterV.vchtype)           	

	  GROUP BY left(dd.date,7) 
) as c  
   
 SET IDENTITY_INSERT #tempOnePtype  off  
end  
 --写入一年的合计数据  
  
if @Period=13 --年合计数据  
Begin  
  
 INSERT INTO  #tempOnePtype (ptypeid,qty,DisCountTotal,CostTotal)    
 SELECT '' [ptypeid],-SUM([qty]) AS [Qty], -SUM([BargainTotal]) AS [discountTotal],-Sum(CostTotal) as CostTotal  
 FROM DlyData dd  
 WHERE billtype=2 and left(date,4)=@Year  
 	and usedtype =case when vchtype in(222,224) then 1 else usedtype end  
	and exists(select 1  from #Ptype_tmp FilterP  where dd.PtypeId = FilterP.TypeId)  
	and exists(select 1  from #Btype_tmp FilterB  where dd.BtypeId = FilterB.TypeId)  
	and exists(select 1  from #Etype_tmp FilterE  where dd.EtypeId = FilterE.TypeId)  
	and exists(select 1  from #Ktype_tmp FilterK where dd.ktypeId = Filterk.KtypeId and selfhelp = @OperatorIsJM)     
	and exists(select 1  from #vchtype_tmp FilterV where dd.vchtype=FilterV.vchtype)           	
 GROUP BY left(dd.date,4)   
end  

 Select * from  #tempOnePtype  
 
  

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/******************************************20130725********************************************/
/******************************************20130801********************************************/

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FN_FZWarnVchArtotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FN_FZWarnVchArtotal]
GO
          
/************************  
 * 查询销售单超期应收款 *  
 * 返回： 查询到的行数  *
 要改需求：
总部职员 ：销售出库，零售，配货单（内部机构单据）
加盟职员 ：销售出库，零售（本加盟机构单据）   
 ***********************/  
Create PROCEDURE FN_FZWarnVchArtotal  
(  	
	@Method     INT,  		 --查询方法 0-查询超过上限的单据 1-查询超过上限并且取消报警的单据  
	@Date       VARCHAR(10), 	 --判断是否到期的日期标准  
	@BType      VARCHAR(50), 	 --单位ID  
	@ifVer      varchar(10)='',  
	@Version    varchar(5) = '',	--版本信息  
	@branchid   varchar(50),
	@Summary    varchar(256),    --摘要
	@Operatorid varchar(50)  
)  
AS  
SET NOCOUNT ON  
DECLARE @ConSQL VARCHAR(8000)  
DECLARE @SQL VARCHAR(8000)  
IF (@Method <> 0 AND @Method <> 1) OR @Date = ''  
   RETURN 0  

SELECT @ifVer = isnull(@ifVer,'')  

  SELECT @ConSQL = ' AND ISNULL(u.Mode, 0) <> 1 AND  ((ISNULL(u.Mode, 0) = 0 AND b.GatheringDate <= ' + CHAR(39) + @Date + CHAR(39) + ')       
   			OR (ISNULL(u.Mode, 0) = 2 AND u.ToDate <= ' + CHAR(39) + @Date + CHAR(39) + '))  
                        and (b.vchcode not in(select draftbillcode from posretailbill))'                          
 
  
 IF @BType = '00000' 
	SELECT @BType = '%' 
 ELSE 
	SELECT @BType = @BType + '%'  

 SELECT @branchid=@branchid+ '%'

If @Version <> 'C' AND @Version <> '' 
begin  
   Select @ConSQL = @ConSQL + ' And (b.vchtype in(select vchtype from vchtype where version like ''%'+ @Version + '%''))'  
   
   if @Version = 'S'  
     Select @ConSQL = @ConSQL + ' And (b.InputNo in(Select Typeid from Employee e ,branch b where e.branchid=b.branchid and b.branchtype=7))'      
   if @Version = 'Z'  
     Select @ConSQL = @ConSQL + ' And (b.InputNo in(Select Typeid from Employee e,branch b where e.branchid=b.branchid and b.branchtype=3))'      
   if @Version = 'J'  
     Select @ConSQL = @ConSQL + ' And (b.InputNo in(Select Typeid from Employee e,branch b where e.branchid=b.branchid and b.branchtype=4))'        
end  	  
SELECT typeid,fullname INTO #btype FROM FN_GetPowerRangeBList(@Operatorid,@BType,'1,2,3,4,6,7') 
SELECT typeid INTO #etype FROM FN_GetPowerRangeEList(@Operatorid,'')
if @ifVer = ''  
begin  
/*
SELECT a.Vchcode,a.VchType,a.BtypeId,a.Number,e.fullname,
a.LimitTime AS GatheringDate,a.Total AS VchTotal,
ISNULL(d.ID,-1) AS DelayID,
SUM(c.total) - SUM(b.total) AS ArTotal,
ISNULL(d.ToDate,'') AS DelayDate,
CASE ISNULL(D.Mode,0) WHEN 1 THEN '取消报警' WHEN 2 THEN '延期报警' ELSE '' END AS DelayMode
FROM dbo.DlyNdx a WITH(NOLOCK)
LEFT JOIN dbo.GatheringDly b WITH(NOLOCK) ON a.Vchcode = b.VchCode
JOIN #btype e ON a.BtypeId = e.typeid
JOIN #etype f ON a.EtypeId = f.typeid
LEFT JOIN dbo.DlyA c WITH(NOLOCK) ON a.Vchcode = c.VchCode
AND 
(
(c.vchtype NOT IN (100, 12) AND (c.AtypeId = '0000100005' OR c.AtypeId LIKE '0000100003%' OR c.AtypeId LIKE '0000100004%'OR c.AtypeId ='0000299999' OR c.AtypeId ='0000200888'OR c.atypeid = '000040000300006'))
OR 
(c.vchtype IN (100, 12) AND (c.atypeid = '0000100005' OR c.atypeid LIKE  '0000100003%' OR c.atypeid LIKE  '0000100004%' OR c.atypeid = '0000299999' OR c.atypeid LIKE  '0000400003%'))
)
LEFT JOIN dbo.UnWarnList d WITH(NOLOCK) ON a.Vchcode = d.TypeID AND d.Type = 6
WHERE
a.Redold = 'F'
AND a.Draft = 2
and (a.VchType = 222 OR a.BranchId LIKE @branchid)
AND a.LimitTime <> ''
AND a.LimitTime <= @Date
AND a.VchType IN (11,12,222,24)
AND ISNULL(d.Mode,0) <> 1
AND (ISNULL(d.Mode,0) = 0 AND a.LimitTime <= @Date OR ISNULL(d.Mode,0) = 2 AND d.ToDate <= @Date)
AND NOT EXISTS(SELECT 1 FROM dbo.PosRetailBill gg WHERE a.Vchcode = gg.DraftBillCode)
GROUP BY a.Vchcode,a.VchType,a.BtypeId,a.Number,e.fullname,
a.LimitTime,a.Total,d.ID,d.ToDate,D.Mode
HAVING SUM(c.total) - SUM(b.total) > 0
*/
SELECT a.Vchcode,a.VchType,a.BtypeId,a.Number,e.fullname,
a.LimitTime AS GatheringDate,a.Total,a.Total AS VchTotal,a.InputNo,
ISNULL(d.ID,-1) AS DelayID,
CAST(0 AS NUMERIC(24,10)) AS ArTotal,
ISNULL(d.ToDate,'') AS DelayDate,
CASE ISNULL(D.Mode,0) WHEN 1 THEN '取消报警' WHEN 2 THEN '延期报警' ELSE '' END AS DelayMode,
a.Summary
INTO #Test
FROM dbo.DlyNdx a WITH(NOLOCK)
JOIN #btype e ON a.BtypeId = e.typeid
JOIN #etype f ON a.EtypeId = f.typeid
LEFT JOIN dbo.UnWarnList d WITH(NOLOCK) ON a.Vchcode = d.TypeID AND d.Type = 6
WHERE
a.Redold = 'F'
AND a.Draft = 2
and (a.VchType = 222 OR a.BranchId LIKE @branchid)
AND a.LimitTime <> ''
AND a.LimitTime <= @Date
AND a.VchType IN (11,12,222,24)
AND ISNULL(d.Mode,0) <> 1
AND (ISNULL(d.Mode,0) = 0 AND a.LimitTime <= @Date OR ISNULL(d.Mode,0) = 2 AND d.ToDate <= @Date)
AND NOT EXISTS(SELECT TOP 1 1 FROM dbo.PosRetailBill gg WHERE a.Vchcode = gg.DraftBillCode)
AND a.Summary like '%'+@Summary+'%'
GROUP BY a.Vchcode,a.VchType,a.BtypeId,a.Number,e.fullname,
a.LimitTime,a.Total,d.ID,d.ToDate,D.Mode,a.InputNo,a.Summary

CREATE UNIQUE CLUSTERED INDEX IDX_VCHCODE ON #Test(Vchcode)
If @Version <> 'C' AND @Version <> '' 
begin  
	DELETE FROM #Test WHERE NOT EXISTS(SELECT 1 FROM dbo.VchType a WHERE #Test.VchType = a.Vchtype AND a.[Version] LIKE '%'+@Version+'%')
 
   if @Version = 'S'  
		DELETE FROM #Test WHERE NOT EXISTS(Select 1 from Employee e ,branch b where e.branchid=b.branchid and b.branchtype=7 AND #Test.InputNo = e.TypeId)
     --Select @ConSQL = @ConSQL + ' And (b.InputNo in(Select Typeid from Employee e ,branch b where e.branchid=b.branchid and b.branchtype=7))'      
   if @Version = 'Z'  
     --Select @ConSQL = @ConSQL + ' And (b.InputNo in(Select Typeid from Employee e,branch b where e.branchid=b.branchid and b.branchtype=3))'
     DELETE FROM #Test WHERE NOT EXISTS(Select 1 from Employee e ,branch b where e.branchid=b.branchid and b.branchtype=3 AND #Test.InputNo = e.TypeId)      
   if @Version = 'J'  
			DELETE FROM #Test WHERE NOT EXISTS(Select 1 from Employee e ,branch b where e.branchid=b.branchid and b.branchtype=4 AND #Test.InputNo = e.TypeId)
     --Select @ConSQL = @ConSQL + ' And (b.InputNo in(Select Typeid from Employee e,branch b where e.branchid=b.branchid and b.branchtype=4))'        
end  	
UPDATE #Test SET ArTotal = b.total
FROM #Test a,
	(
		SELECT c.Vchcode,SUM(CASE WHEN atypeid IN ('0000299999','0000200888') THEN -1*Total ELSE Total END) AS Total FROM dbo.DlyA c WITH(NOLOCK)
		where c.VchType IN (11,12,222,24)
		AND 
		(
		(c.vchtype NOT IN (12) AND (c.AtypeId = '0000100005' OR c.AtypeId LIKE '0000100003%' OR c.AtypeId LIKE '0000100004%'OR c.AtypeId ='0000299999' OR c.AtypeId ='0000200888'OR c.atypeid = '000040000300006'))
		OR 
		(c.vchtype IN (12) AND (c.atypeid = '0000100005' OR c.atypeid LIKE  '0000100003%' OR c.atypeid LIKE  '0000100004%' OR c.atypeid = '0000299999' OR c.atypeid LIKE  '0000400003%'))
		)
		GROUP BY c.VchCode
	) b where a.vchcode = b.vchcode
	
update #test set artotal = artotal - b.total
from #test a,
(
select vchcode,sum(total) AS Total FROM dbo.GatheringDly WITH(NOLOCK) WHERE draft=2 GROUP BY vchcode
)	b WHERE a.Vchcode = b.vchcode
DELETE FROM #Test WHERE ArTotal <= 0
SELECT * FROM #Test

	SELECT @SQL = '  
	 SELECT   
	  b.VchCode, b.VchType, b.BTypeID, b.Number, b.bFullName AS FullName,   
	  b.GatheringDate, b.VchTotal AS Total, b.BalanceTotal AS ArTotal,  
	  ISNULL(u.ID, -1) AS DelayID, ISNULL(u.ToDate, ' + CHAR(39) + CHAR(39) + ') AS DelayDate,  	                  
	  DelayMode = CASE ISNULL(u.Mode, 0)   
	     WHEN 1 THEN ' + CHAR(39) + '取消报警' + CHAR(39) +   
	   ' WHEN 2 THEN ' + CHAR(39) + '延期报警' + CHAR(39) +   
	   ' ELSE ' + CHAR(39) + CHAR(39) + ' END  
	 FROM   
	   --view_zz_VchBalance2 b  
	   view_FN_zz_VchBalance2 b	
	   LEFT JOIN UnWarnList u ON CONVERT(VARCHAR(50), b.VchCode) = u.TypeID AND ISNULL(u.Type, 0) = 6  
	 WHERE   
	  b.BTypeID LIKE ' + CHAR(39) + @BType + CHAR(39) + '  AND b.Draft = 2
	  and  b.btypeid in (select typeid from FN_GetPowerRangeBList('''+@Operatorid+''','''',''1,2,3,4,6,7''))  
	  and  b.etypeid in (select typeid from FN_GetPowerRangeEList('''+@Operatorid+''',''''))  
	  AND b.GatheringDate <> ' + CHAR(39) + CHAR(39) + '   
	  AND b.GatheringDate <= ' + CHAR(39) + @Date + CHAR(39) + '  
	  --AND b.VchType in(11,12,222,250,24)  	  
	  --AND b.branchid like ' + CHAR(39) + @branchid + CHAR(39) +'
	  AND b.VchType in(11,12,222,24)  	  	
	  AND b.branchid LIKE Case WHEN VchType=222 Then ''%'' ELSE   '''+@branchid+''' END	  --配货单的机构 branchid 是收货机构，对配货类不过滤机构，都是总部对加盟商的应收
	  AND (b.BalanceTotal > 0)' + @ConSQL  
	  
	--EXEC(@SQL)  
	print @Sql  
end  

if @ifVer = 'V'   
begin  
  
      if Exists( SELECT b.vchcode as Num     
 FROM   
   view_zz_VchBalance2 b  
   LEFT JOIN UnWarnList u ON CONVERT(VARCHAR(50), b.VchCode) = u.TypeID AND ISNULL(u.Type, 0) = 6  
 WHERE   
  b.BTypeID LIKE  @BType  
  AND b.GatheringDate <> ''   
  AND b.GatheringDate <=  @Date   
  AND b.VchType in(11,12,222,250,24)  
  AND b.Draft = 2  
  AND (b.BalanceTotal > 0)  
                AND ISNULL(u.Mode, 0) <> 1 AND   
     ((ISNULL(u.Mode, 0) = 0 AND b.GatheringDate <=  @Date )   
   OR (ISNULL(u.Mode, 0) = 2 AND u.ToDate <=  @Date ))  
                 )  
      begin  
         Select 1 as Num  
      end  
      else  
         Select 0 as Num  
end  
  
RETURN @@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].[FzUpdateP]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FzUpdateP]
GO






/****** Object:  Stored Procedure dbo.F_B_UpdateP    Script Date: 2004-09-02 8:40:11 ******/
--  ********************************************************************************************
--  ||                                                                                        
--  ||   过程名称： F_B_UpdateP                                    
--  ||   过程功能：添加基本信息--仓库
--  ||=========================================================================================
--  ||   参数说明：  参数名称         类型            意义                     输入输出
--  ||            -----------------------------------------------------------------------------
--  ||  	@Parid 		varchar(50),                                             --父亲ID号1
--  ||  	@dbname        	varchar(30),                                             --操作的数据库表名2
--  ||  	@FullName 	varchar(66),                                             --商品全名3
--  ||  	@Name		varchar(30),                                             --商品简名4
--  ||  	@UserCode 	varchar(26),                                             --用户编码5
--  ||  	@Standard 	varchar(20),                                             --商品规格6
--  ||  	@Type	 	varchar(20),                                             --商品类型7
--  ||  	@Area	 	varchar(30),                                             --商品产地8
--  ||  	@Unit1 		varchar(8),                                               --商品单位1  9
--  ||  	@Unit2 		varchar(8),                                               --商品单位2  10
--  ||  	@UnitRate1 	numeric(24,10),                                        --单位关系1  11
--  ||  	@UnitRate2 	numeric(24,10),                                        --单位关系2  12
--  ||  	@preprice1 	numeric(24,10),                                        --预设售价1  13
--  ||  	@preprice2 	numeric(24,10),                                        --预设售价2  14
--  ||  	@preprice3 	numeric(24,10),                                        --预设售价3  15
--  ||  	@preprice4 	numeric(24,10),                                        --预设售价4  16
--  ||	@retailprice        numeric(24,10),                                         零售价
--  ||        @minprice          numeric(24,10),			             最低售价
--  ||  	@LifeMonth 	smallint,                                                    --保质期月17
--  ||  	@LifeDay 	smallint,                                                    --保质期天18
--  ||  	@CostMode	smallint,                                                    --成本算法19
--  ||  	@Comment 	varchar(256),                                           --备注20
--  ||  	@namepy	varchar(60),                                             --全名简拼21
--  ||  	@Barcode	varchar(30),                                             --商品条码22
--  ||  	@sizegroupid      int,                                                           --尺码组23
--  ||  	@colorgroupid    int,                                                           --颜色组24
--  ||  	@breakwarn       numeric(24,10),                                       --断码报警数25
--  ||  	@Formatid           varchar(10),                                             --条码格式26
--  ||  	@cspz                int,                                                            --颜色尺码配置
--  ||  	@backRec        int  output,--
--  ||  	@material	int,                                                            --面料
--  ||  	@season           int,                                                           --季节
--  ||  	@category         int,                                                           --品牌
--  ||  	@year               int,                                                            --年度
--  ||               -- @SPPIC              image,                                                      -- 商品图片
--  ||  	@trade                bit,                                                            --可否换货0：不能换货，1：可以换货
--  ||  	@stop                 bit                                                             -- 是否停用
--  ||        @discount          int					折扣0
--  ||        @discount1        int                                                              折扣1
--  ||        @discount2	int					折扣2
--  ||        @discount3	int					折扣3
--  ||=========================================================================================   
--  ||    返回值： 值               说明               
--  ||                   -1                  -- 数据库操作失败！
--  ||                   -2                -- 此记录已经过账，不能再分类！
--  ||                   -3                  -- 父亲ID号不存在！
--  ||                   -4              名称不能相同
--  ||	-5		  编码不能相同
--  ||	－7		  名称和编码不能同时相同	
--  ||                   -6                 有相同条码的记录存在
--  ||=========================================================================================

/*
cqhua 2011-8-29
尺码组改变
*/

CREATE PROCEDURE FzUpdateP
    (
      @typeId VARCHAR(50),--商品编码
      @dbname VARCHAR(30),--所操作的数据表名
      @FullName VARCHAR(66),--商品全名
      @Name VARCHAR(30),--商品简名
      @UserCode VARCHAR(26),--用户编码
      @Standard VARCHAR(20),--商品规格
      @Type VARCHAR(20),--商品类型
      @Area VARCHAR(30),--商品产地
      @Unit1 VARCHAR(8),--商品单位1
      @Unit2 VARCHAR(8),--商品单位2
      @UnitRate1 NUMERIC(24, 10),--单位关系1
      @UnitRate2 NUMERIC(24, 10),--单位关系2
      @preprice1 NUMERIC(24, 10),--预设售价1
      @preprice2 NUMERIC(24, 10),--预设售价2
      @preprice3 NUMERIC(24, 10),--预设售价3
      @preprice4 NUMERIC(24, 10),--预设售价4
      @retailprice NUMERIC(24, 10),--零售价
      @minprice NUMERIC(24, 10),--最低售价
      @LifeMonth SMALLINT,--保质期月
      @LifeDay SMALLINT,--保质期日
      @CostMode SMALLINT,--成本算法
      @Comment VARCHAR(250),--备注
      @namepy VARCHAR(60),--商品全名简拼
      @Barcode VARCHAR(30),--商品条码
      @sizegroupid INT,--尺码组Id 
      @colorgroupid INT,--颜色组Id
      @breakwarn NUMERIC(24, 10),  -- 断码报警数
      @cspz INT,       --
      @material VARCHAR(30),--面料
      @season INT, --季节
      @category INT, --品牌
      @year INT,  --年度
      @FORMATID VARCHAR(10),                                            --条码格式
         --    @SPPIC              image,                                                      -- 商品图片
      @trade INT,                                                            --可否换货0：不能换货，1：可以换货
      @stop BIT,  --是否停用
      @discount NUMERIC(24, 10),
      @discount1 NUMERIC(24, 10),
      @discount2 NUMERIC(24, 10),
      @discount3 NUMERIC(24, 10),
      @changechild INT,
      @StopDate VARCHAR(10) = '',	-- 是否修改儿子的成本算法 0 不修改, 1 修改
      @ColorIdList VARCHAR(1000) = '',
      @SizeIdList VARCHAR(1000) = '',
      @iPa1 INT,
      @iPa2 INT,
      @iPa3 INT,
      @iPa4 INT,
      @IssueDate VARCHAR(10) = '',
      @Custom1 VARCHAR(255),
      @Custom2 VARCHAR(255),
      @Custom3 VARCHAR(255),
      @Custom4 VARCHAR(255),
      @Custom5 VARCHAR(255),
      @btypeid VARCHAR(50) = '',
      @changerule INT,
	  @singleunit INT = 0,
      @BuyUnit INT = 1,
      @SaleUnit INT = 1,
      @PhUnit INT =1,
      @GoodsUnit INT = 1,
      @AttributeId1 INT = 0,                      --与辅助属性类型对应
	  @AttributeId2 INT = 0,
      @AttributeId3 INT = 0,
	  @AttributeId4 INT = 0,
	  @AttributeId5 INT = 0,
	  @AttributeId6 INT = 0,
	  @AttributeId7 INT = 0,
	  @AttributeId8 INT = 0,
	  @IsDeleteUniq INT = 0,
	  @IsChangeAttribute BIT, --是否改变了辅助属性
	  @ChangeAttributeIdList VARCHAR(50)='',--修改辅助属性编号列表
	  @IsChangeBar BIT, --是否改变了条码格式
	  @IsChangeBtype BIT, --是否改变了供应商
	  @IsChangeBarcode BIT, --是否改变了商品条码
	  @IsChangeColor BIT, --是否改变了颜色
	  @IsChangeSize BIT, --是否改变了尺码
	  @IsChangePrice BIT --是否改变了价格	  
    )
AS 
    SET nocount ON
    DECLARE @OldCostMode INT
    DECLARE @szptypeid VARCHAR(50)
    DECLARE @szKtypeid VARCHAR(50)
    DECLARE @Qty NUMERIC(24, 10)
    DECLARE @Total NUMERIC(24, 10)
    DECLARE @lsonnum INT
    DECLARE @ROOT_ID VARCHAR(50)
    DECLARE @oldBar VARCHAR(30)        
    DECLARE @oldBcon VARCHAR(30)
    DECLARE @oldStop BIT
    DECLARE @BarConID INT      
    DECLARE @oldCGid INT,
        @oldSGid INT     
    DECLARE @cid INT,
        @cbar VARCHAR(10),
        @sid INT,
        @sbar VARCHAR(10),
        @bar VARCHAR(50)   
    DECLARE @UpdateTag INT,@UpdateTagAttribute INT,@UpdateTagBar INT,@UpdateTagPrice INT
	DECLARE @ColorIdListOld varchar(2000)	
	declare @re int	
	DECLARE @SizeNameList varchar(2000) 
	EXEC @re =CheckGroupCanChange  @typeId,@SizeIdList,@SizeNameList OutPut
	IF @re<>0 GOTO error154
    SELECT  @OldCostMode = [costmode],
            @oldBar = barcode,
            @oldBcon = formatid,
			@ColorIdListOld=ColorIdList,
			@oldStop = [Stop]
    FROM    ptype
    WHERE   typeId = @typeId
	
    IF @oldBar <> @BarCode
        OR @oldBcon <> @FORMATID
        OR @IsDeleteUniq = 1  --系统条码修改后，如果存在唯一码，要删除 ptypeuniquecode
        BEGIN
            DELETE  FROM ptypeuniquecode
            WHERE   ptypeid = @Typeid
            DELETE  FROM PtypeUniqueCheck
            WHERE   ptypeid = @Typeid	
        END
	
    SELECT  @ROOT_ID = '00000'
    DECLARE @Stats1 INT
    DECLARE @Stats2 INT
    SELECT  @Stats1 = stats
    FROM    syscon
    WHERE   [order] = 81
    SELECT  @Stats2 = stats
    FROM    syscon
    WHERE   [order] = 82
    IF @Stats1 = 1 
        IF EXISTS ( SELECT  [typeid]
                    FROM    ptype
                    WHERE   typeId <> @typeId
                            AND ( fullname = @fullname
                                  AND [deleted] <> 1
                                ) ) 
            GOTO error114
--名称不能相同
    IF @Stats2 = 1 
        IF EXISTS ( SELECT  [typeid]
                    FROM    ptype
                    WHERE   typeId <> @typeId
                            AND ( usercode = @usercode
                                  AND [deleted] <> 1
                                ) ) 
            GOTO error115
--编码不能相同
    IF @Stats1 = 0
        AND @Stats2 = 0 
        IF EXISTS ( SELECT  [typeid]
                    FROM    ptype
                    WHERE   typeId <> @typeId
                            AND ( fullname = @fullname
                                  AND usercode = @usercode
                                  AND [deleted] <> 1
                                ) ) 
            GOTO error117
    IF EXISTS ( SELECT  getid
                FROM    dbo.GetIdListTable(@ColorIdList)
                WHERE   getid NOT IN ( SELECT   colorid
                                       FROM     color ) ) 
        GOTO error1117
    IF EXISTS ( SELECT  getid
                FROM    dbo.GetIdListTable(@SizeIdList)
                WHERE   getid NOT IN ( SELECT   sizeid
                                       FROM     size ) ) 
        GOTO error1118

    IF @Issuedate = '' 
        SET @Issuedate = CONVERT(CHAR(10), GETDATE(), 121)
      
    IF ( LEN(RTRIM(LTRIM(@Barcode))) > 0 ) 
        BEGIN  
            IF EXISTS ( SELECT  [typeid]
                        FROM    ptype
                        WHERE   [typeId] <> @typeId
                                AND ( Barcode = @Barcode )
                                AND [deleted] <> 1 ) 
                GOTO error200
        END
    GOTO UpdateOne
    UpdateOne:
--	如果 sonnum>0 则修改儿子成本算法，并且合并库存
--只有加权了。所以不需要了
-- 	if (@lsonnum > 0) and (@changechild = 1)
-- 	begin
-- 		select @szptypeid = @typeid + '%'
-- 		exec @stats1 = changecostmode 1, @szptypeid, @costmode -- 修改成本算法，合并期初批次
-- 		if @stats1 < 0 goto error1		
-- 		exec @stats1 = changecostmode 2, @szptypeid, @costmode -- 修改成本算法，合并当前批次
-- 		if @stats1 < 0 goto error1		
-- 	end

	IF @SizeIdList ='1'
		SET @sizegroupid =1
    EXEC [dbo].[XW_GetUpdateTag] 'Ptype', @UpdateTag OUTPUT
    UPDATE  [dbo].[ptype]
    SET     [UserCode] = @UserCode,
            [FullName] = @FullName,
            [Name] = @Name,
            [Standard] = @Standard,
            [Type] = @Type,
            [Area] = @Area,
            [Unit1] = @Unit1,
            [Unit2] = @Unit2,
            [UnitRate1] = @UnitRate1,
            [UnitRate2] = @UnitRate2,
            --retailprice = @retailprice,
            [costmode] = @CostMode,
            [Comment] = @Comment,
            [namepy] = @namepy,
            [Barcode] = @Barcode,
            breakwarn = @breakwarn,
            formatid = @FORMATID,
            cspz = @cspz,
            trade = @trade,
            stop = @stop,
            StopDate = @StopDate,
            issueDate = @issueDate,
            ColorIdList = @ColorIdList,
            SizeIdList = @SizeIdList,
            updateTag = @UpdateTag,
            PCustom1 = @Custom1,
            PCustom2 = @Custom2,
            PCustom3 = @Custom3,
            PCustom4 = @Custom4,
            PCustom5 = @Custom5,
            btypeid1 = @btypeid,
            changerule = @changerule,
			sizegroupid=@sizegroupid,
			singleunit = @singleunit,
            BuyUnit = @BuyUnit,
            SaleUnit = @SaleUnit,
            PhUnit = @PhUnit,
            GoodsUnit = @GoodsUnit,
            mininumprice = @minprice
    WHERE   [typeId] = @typeId
   
	IF @IsChangeAttribute=1 --更改了辅助属性
	BEGIN
		EXEC [dbo].[XW_GetUpdateTag] 'PtypeAttribute', @UpdateTagAttribute OUTPUT
		UPDATE dbo.Ptype SET UpdateTagAttribute=@UpdateTagAttribute WHERE   [typeId] = @typeId
	END
	IF @IsChangeBar=1 --更改了条码格式
	BEGIN
		EXEC [dbo].[XW_GetUpdateTag] 'PtypeBar', @UpdateTagBar OUTPUT
		UPDATE dbo.Ptype SET UpdateTagBar=@UpdateTagBar WHERE   [typeId] = @typeId
	END
	ELSE
	BEGIN
		IF   (@IsChangeBarcode=1 AND EXISTS (SELECT 1 FROM dbo.Ptype p INNER JOIN dbo.BarCodeItem bc ON p.FormatID=bc.PlanId WHERE bc.ItemNo='01' AND p.TypeID=@typeId ) ) --更改了商品条码
		OR (@IsChangeBtype=1 AND EXISTS (SELECT 1 FROM dbo.Btype b INNER JOIN dbo.Ptype p ON b.TypeId=p.btypeid1 INNER JOIN dbo.BarCodeItem bc ON p.FormatID=bc.PlanId WHERE bc.ItemNo='12' AND p.TypeID=@typeId  AND b.TypeId=@btypeid ) ) --更改了供应商		
		OR (@IsChangeColor=1 AND EXISTS (SELECT 1 FROM dbo.GetIdListTable(@ColorIdList) c INNER JOIN dbo.PtypeColor pc ON c.GetId=pc.ColorId INNER JOIN dbo.Ptype p ON p.TypeID=pc.PtypeId INNER JOIN dbo.BarCodeItem bc ON p.FormatID=bc.PlanId WHERE bc.ItemNo='02' AND p.TypeID=@typeId ) ) --更改了颜色
		OR (@IsChangeSize=1 AND EXISTS (SELECT 1 FROM dbo.GetIdListTable(@SizeIdList) s INNER JOIN dbo.PtypeSize ps ON s.GetId=ps.SizeID INNER JOIN dbo.Ptype p ON p.TypeID=ps.PtypeId INNER JOIN dbo.BarCodeItem bc ON p.FormatID=bc.PlanId WHERE bc.ItemNo='03' AND p.TypeID=@typeId ) ) --更改了尺码
		BEGIN
			EXEC [dbo].[XW_GetUpdateTag] 'PtypeBar', @UpdateTagBar OUTPUT
			UPDATE dbo.Ptype SET UpdateTagBar=@UpdateTagBar WHERE   [typeId] = @typeId
		END
		ELSE IF (@IsChangeAttribute=1 AND EXISTS(SELECT 1 FROM dbo.PtypeAttribute pa INNER JOIN AssistAttribute aa ON pa.AttributeID=aa.AttributeId INNER JOIN dbo.Ptype p ON pa.PtypeId=p.TypeID INNER JOIN dbo.BarCodeItem bc ON p.FormatID=bc.PlanId WHERE aa.TypeID=1 AND aa.TypeID IN (SELECT getid FROM GetIdListTable(@ChangeAttributeIdList)) AND bc.ItemNo='04' AND p.TypeID=@typeId))--更改了辅助属性1
			  OR (@IsChangeAttribute=1 AND EXISTS(SELECT 1 FROM dbo.PtypeAttribute pa INNER JOIN AssistAttribute aa ON pa.AttributeID=aa.AttributeId INNER JOIN dbo.Ptype p ON pa.PtypeId=p.TypeID INNER JOIN dbo.BarCodeItem bc ON p.FormatID=bc.PlanId WHERE aa.TypeID=2 AND aa.TypeID IN (SELECT getid FROM GetIdListTable(@ChangeAttributeIdList)) AND  bc.ItemNo='05' AND p.TypeID=@typeId))--更改了辅助属性2
			  OR (@IsChangeAttribute=1 AND EXISTS(SELECT 1 FROM dbo.PtypeAttribute pa INNER JOIN AssistAttribute aa ON pa.AttributeID=aa.AttributeId INNER JOIN dbo.Ptype p ON pa.PtypeId=p.TypeID INNER JOIN dbo.BarCodeItem bc ON p.FormatID=bc.PlanId WHERE aa.TypeID=3 AND aa.TypeID IN (SELECT getid FROM GetIdListTable(@ChangeAttributeIdList)) AND  bc.ItemNo='06' AND p.TypeID=@typeId))--更改了辅助属性3
			  OR (@IsChangeAttribute=1 AND EXISTS(SELECT 1 FROM dbo.PtypeAttribute pa INNER JOIN AssistAttribute aa ON pa.AttributeID=aa.AttributeId INNER JOIN dbo.Ptype p ON pa.PtypeId=p.TypeID INNER JOIN dbo.BarCodeItem bc ON p.FormatID=bc.PlanId WHERE aa.TypeID=4 AND aa.TypeID IN (SELECT getid FROM GetIdListTable(@ChangeAttributeIdList)) AND  bc.ItemNo='07' AND p.TypeID=@typeId))--更改了辅助属性4
			  OR (@IsChangeAttribute=1 AND EXISTS(SELECT 1 FROM dbo.PtypeAttribute pa INNER JOIN AssistAttribute aa ON pa.AttributeID=aa.AttributeId INNER JOIN dbo.Ptype p ON pa.PtypeId=p.TypeID INNER JOIN dbo.BarCodeItem bc ON p.FormatID=bc.PlanId WHERE aa.TypeID=5 AND aa.TypeID IN (SELECT getid FROM GetIdListTable(@ChangeAttributeIdList)) AND  bc.ItemNo='08' AND p.TypeID=@typeId))--更改了辅助属性5
			  OR (@IsChangeAttribute=1 AND EXISTS(SELECT 1 FROM dbo.PtypeAttribute pa INNER JOIN AssistAttribute aa ON pa.AttributeID=aa.AttributeId INNER JOIN dbo.Ptype p ON pa.PtypeId=p.TypeID INNER JOIN dbo.BarCodeItem bc ON p.FormatID=bc.PlanId WHERE aa.TypeID=6 AND aa.TypeID IN (SELECT getid FROM GetIdListTable(@ChangeAttributeIdList)) AND  bc.ItemNo='09' AND p.TypeID=@typeId))--更改了辅助属性6
			  OR (@IsChangeAttribute=1 AND EXISTS(SELECT 1 FROM dbo.PtypeAttribute pa INNER JOIN AssistAttribute aa ON pa.AttributeID=aa.AttributeId INNER JOIN dbo.Ptype p ON pa.PtypeId=p.TypeID INNER JOIN dbo.BarCodeItem bc ON p.FormatID=bc.PlanId WHERE aa.TypeID=7 AND aa.TypeID IN (SELECT getid FROM GetIdListTable(@ChangeAttributeIdList)) AND  bc.ItemNo='10' AND p.TypeID=@typeId))--更改了辅助属性7
			  OR (@IsChangeAttribute=1 AND EXISTS(SELECT 1 FROM dbo.PtypeAttribute pa INNER JOIN AssistAttribute aa ON pa.AttributeID=aa.AttributeId INNER JOIN dbo.Ptype p ON pa.PtypeId=p.TypeID INNER JOIN dbo.BarCodeItem bc ON p.FormatID=bc.PlanId WHERE aa.TypeID=8 AND aa.TypeID IN (SELECT getid FROM GetIdListTable(@ChangeAttributeIdList)) AND  bc.ItemNo='11' AND p.TypeID=@typeId))--更改了辅助属性8
		BEGIN
			EXEC [dbo].[XW_GetUpdateTag] 'PtypeBar', @UpdateTagBar OUTPUT
			UPDATE dbo.Ptype SET UpdateTagBar=@UpdateTagBar WHERE   [typeId] = @typeId
		END		
	END
	IF @IsChangePrice=1 --更改了价格
	BEGIN
		EXEC [dbo].[XW_GetUpdateTag] 'PtypePrice', @UpdateTagPrice OUTPUT
		UPDATE dbo.Ptype SET UpdateTagPrice=@UpdateTagPrice WHERE   [typeId] = @typeId
	END
    
    IF @@error < 0 
        GOTO error1
    DELETE  ptypeColor
    WHERE   ptypeid = @typeId
          
    IF @@error <> 0 --写数据失败回滚事务
        BEGIN
            GOTO error1
        END  
    INSERT  INTO PtypeColor ( Ptypeid, Colorid )
            SELECT  @typeId,
                    getid
            FROM    dbo.GetIdListTable(@ColorIdList)
    IF @@error <> 0 --写数据失败回滚事务
        BEGIN
            GOTO error1
        END  

    DELETE  ptypeSize
    WHERE   ptypeid = @typeId
          
    IF @@error <> 0 --写数据失败回滚事务
        BEGIN
            GOTO error1
        END  
    INSERT  INTO ptypeSize ( Ptypeid, Sizeid )
            SELECT  @typeId,
                    getid
            FROM    dbo.GetIdListTable(@SizeIdList)
    IF @@error <> 0 --写数据失败回滚事务
        BEGIN
            GOTO error1
        END   
    IF @stop = 0 
        BEGIN
            UPDATE  ptype
            SET     stop = 0,
                    updateTag = @UpdateTag
            WHERE   typeid = LEFT(@typeId, LEN(typeid))  --下级启用，上级也启用
        END
    IF @stop = 1 
        BEGIN
            IF EXISTS ( SELECT  *
                        FROM    ptype
                        WHERE   sonnum > 0
                                AND typeid = @typeid ) 
                UPDATE  ptype
                SET     stop = 1,
                        updateTag = @UpdateTag
                WHERE   LEFT(typeid, LEN(@typeid)) = @typeid
        END
    
	--IF @oldStop <> @stop
	--update dbo.Ptype set [stop] =@Stop where LEFT(typeid, LEN(@typeid)) = @typeid   
			
	--商品颜色不包含在已有的颜色组中，新增颜色组
	--IF @ColorIdListOld<>@ColorIdList and not EXISTS(SELECT * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZCS') 
	--BEGIN
	--	IF OBJECT_ID('tempdb..#TT') IS NOT NULL
	--		DROP TABLE #TT
	--	SELECT * INTO #TT FROM dbo.fn_split(@colorIdlist,',')
		
	--	IF NOT EXISTS (SELECT 1 FROM colorGroupRelation c INNER JOIN #TT t ON c.colorid=t.a GROUP BY c.ColorGroupId HAVING(COUNT(1)=(SELECT COUNT(1) FROM #TT)))
	--	BEGIN
	--		INSERT INTO colorGroup(name,remark,sysrow,[order])  select (select '系统颜色组'+(select Convert(varchar(10),isnull(max(colorGroupid),1)) from colorGroup)) as name,'系统升级自动生成',0,10000
	--		INSERT INTO colorGroupRelation(colorGroupID,colorid,rec,[order]) select @@identity,getid,0,iorder from  GetIdListTable(@colorIdlist)
	--	END
	--	UPDATE Ptype SET ColorGroupID = 1 WHERE   typeid=@Typeid AND ColorGroupID=0 AND @colorIdlist ='1'
		
	--	UPDATE Ptype SET ColorGroupID = S.Colorgroupid
	--	FROM (
	--		SELECT TOP 1 ColorGroupId
	--		FROM colorGroupRelation 
	--		WHERE ColorGroupId IN(
	--		SELECT c.ColorGroupId FROM colorGroupRelation c INNER JOIN #TT t ON c.colorid=t.a 
	--		GROUP BY c.ColorGroupId HAVING(COUNT(1)=(SELECT COUNT(1) FROM #TT))
	--		)
	--		GROUP BY ColorGroupId
	--		ORDER BY COUNT(1)
	--	) S
	--	WHERE typeid=@Typeid
	--	select @@ROWCOUNT
	--END



    IF ( LEN(RTRIM(LTRIM(@Barcode))) = 0 ) 
        DELETE  ptypebar
        WHERE   ptypeid = @Typeid
    ELSE 
        BEGIN  
            IF EXISTS ( SELECT  ptypeid
                        FROM    PtypeBar
                        WHERE   Ptypeid = @Typeid ) 
                UPDATE  ptypebar
                SET     FullBarCode = REPLACE(FullBarCode, @oldBar, @Barcode)
                WHERE   Ptypeid = @Typeid
            ELSE 
                GOTO updateb
        END
    IF @@error <> 0 
        GOTO error1

    IF ( LEN(RTRIM(LTRIM(@Barcode))) > 0 ) 
        GOTO updateb  
    GOTO succee
     
    updateb:

    BEGIN
        DELETE  ptypebar
        WHERE   Ptypeid = @typeid   --改成全删除0026093: 商品条码和颜色尺码的条码都是1位，商品条码一改变，系统码的最后一位也跟着变了 
      --and (not exists(select 1 from (select @typeid as typeid,getid as colorid from dbo.GetIDListTable(@ColorIdList) ) ls  
      --                where ls.typeid = ptypebar.ptypeid and ls.colorid = ptypebar.colorid) 
      --     or not exists(select 1 from (select @typeid as typeid,getid as sizeid from dbo.GetIDListTable(@sizeIdList) ) ls1  
     --                 where ls1.typeid = ptypebar.ptypeid and ls1.sizeid = ptypebar.sizeid) 
     --or @oldBcon <> @FORMATID)
          
--    if @oldBar <> @BarCode     
        IF ( SELECT MAX(Sonnum)
             FROM   Ptype
             WHERE  typeid = @typeid
           ) = 0 
            BEGIN
            EXEC GeneratePtypeBar @Formatid,@typeId,@cspz,@Barcode,@ColorIdList,@SizeIdList,@AttributeId1,@AttributeId2,@AttributeId3,@AttributeId4,@AttributeId5,@AttributeId6,@AttributeId7,@AttributeId8,@Btypeid    
            END
    END     

     
    IF @FORMATID = 'bsc' 
        SELECT  @BarConID = 1
    ELSE 
        IF @FORMATID = 'bcs' 
            SELECT  @BarConID = 0
        ELSE 
            SELECT  @BarConID = 2
    UPDATE  sysdata
    SET     subvalue = @BarConID
    WHERE   subno = 25

    succee:   
    RETURN 0
    error1:
    RETURN -1
    error2:
    RETURN -2
    error114:
    RETURN -4
    error115:
    RETURN -5 
    error117:
    RETURN -7
    error200:
    RETURN -6
    error1117:
    RETURN -17
--颜色不存存在
    error1118:
    RETURN -18
	
	error154:
    RETURN -154
--尺码不存存在





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS 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_FZPtypeRWPrice_build]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FN_FZPtypeRWPrice_build]
GO





CREATE  Proc FN_FZPtypeRWPrice_build
(
	@ptypeid 		VARCHAR(50),	
	@date           	varchar(10),    -- 修改日期
	@etypeid		VARCHAR(50),    -- 经手人
	@inputno		VARCHAR(50),    -- 操作员
	@remark			varchar(200),   -- 备注
	@pricetypeid		varchar(50),	--要修改的价格
	@seltypeid		varchar(50),    --在哪个价格基础(操作)
	@operator		varchar(5),     --操作符合
	@price			numeric(24,10)  --调整值
)
AS

BEGIN TRAN  --开始事务
 
declare @tempTypeid varchar(50)
declare typeid_cursor cursor for
select typeid from ptype where typeid like @ptypeid+'%' and deleted = 0 and sonnum=0
open typeid_cursor
fetch next from typeid_cursor into @tempTypeid
while @@FETCH_STATUS = 0
begin

--第一步 生成原价格临时表(把要修改之前的价格记录下来)
if object_id('tempdb..#sourceprice') is not null Drop Table #SourcePrice
Create Table #sourceprice(ptypeid VARCHAR(50), sourceprice numeric(24,10))


IF (LEFT(@priceTypeid,6)='YSCGZK' OR  LEFT(@priceTypeid,4)='YSZK')--预设采购折扣,--预设折扣(如果用户输入的是0，含义等同于100)
BEGIN
	IF @price=0
	BEGIN
		SET @price=100
	END
END


IF (LEFT(@priceTypeid,6)='YSCGZK' OR  LEFT(@priceTypeid,4)='YSZK')--预设采购折扣,--预设折扣
BEGIN
	Insert into #sourceprice 
	select  p.typeid as ptypeid, isnull(pp.price, 100) sourceprice 
			from ptype p left join ptypeprice pp 
			on p.typeid = pp.ptypeid and pp.pricetypeid = @priceTypeid
			where p.typeid = @tempTypeid  and p.deleted = 0
			order by ptypeid
END
ELSE
BEGIN
	Insert into #sourceprice
			select  p.typeid as ptypeid, isnull(pp.price, 0) sourceprice 
			from ptype p left join ptypeprice pp 
			on p.typeid = pp.ptypeid and pp.pricetypeid = @priceTypeid
			where p.typeid = @tempTypeid and p.deleted = 0
			order by ptypeid
			
END

/****************************************************************************************/
--事务放在CS代码中了 cqhua 2011-1-11
--BEGIN TRAN

DECLARE @priceTempValue numeric(24,10) 
DECLARE @priceValue numeric(24,10)     --最后往数据库存放的价格
DECLARE @sql nvarchar(2000)
SET @priceTempValue=0
SET @priceValue=0

--验证
--判断要改的价格的值是否有小于0,大于999999						
IF @price<0 or @price>999999  --1.直接验证输入的值
BEGIN
	ROLLBACK TRANSACTION    
 	CLOSE typeid_cursor  
 	DEALLOCATE typeid_cursor
	--drop table #sourceprice
	RETURN -1
END

--2.有在最近进价的基础上改变价格的情况		
IF @seltypeid='recprice'
BEGIN
	SELECT @priceTempValue=recprice FROM ptype WHERE typeid=@tempTypeid
	SET @priceTempValue=ISNULL(@priceTempValue,0)
	SET @priceValue=0
	SET @sql= 'DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
		EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
		select @priceValue= Round(' +  cast(@priceTempValue as varchar(50)) + @operator + cast(@price as varchar(50)) + ',@dig_price)'			
	EXEC sp_executesql @sql,N' @priceValue numeric(24,10) out',@priceValue out
	IF @priceValue<0 or @priceValue>999999
	BEGIN	
		/*
		IF @@error <> 0 
		BEGIN
			goto error1
		END
		*/
		ROLLBACK TRANSACTION  
        	CLOSE typeid_cursor  
 		DEALLOCATE typeid_cursor 
		--drop table #sourceprice
  		return -1
	END
END
ELSE
BEGIN
	IF @seltypeid<>''--在其他用户自己添加的价格基础上,修改某个价格	
	BEGIN
		SET @priceValue=0		
		SET @sql='SELECT @priceValue=Price  FROM PtypePrice WHERE PriceTypeid='+char(39)+CAST(@seltypeid as varchar(50))+char(39)+' and Ptypeid='+char(39)+@tempTypeid+char(39)+'  '		
	IF @seltypeid = 'costprice'
	BEGIN
		SET @priceValue=0
		
 		SET @sql='
 		DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
		EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
		
 		SELECT @priceValue=Convert(numeric(24,10),Round(Convert(numeric(24,10),sum(total))/Convert(numeric(24,10),sum(qty)),@dig_price)) FROM GoodsStocks WHERE KtypeId in (select TypeId from stock where BranchId not like ''00004%'') and Ptypeid='+char(39)+@tempTypeid+char(39)+'  '     
	END	 
		PRINT @sql
		EXEC sp_executesql @sql,N' @priceValue numeric(24,10) out',@priceValue out 
		set @priceValue = isnull(@priceValue,0)
		PRINT @priceValue
		IF (LEFT(@seltypeid,6)='YSCGZK' OR  LEFT(@seltypeid,4)='YSZK')
		BEGIN
			IF @priceValue=0
			   SET @priceValue=100
		END
		--SELECT @priceValue 得到某个价格基础上的价格,下面再进行组合
		SET @priceTempValue=0
		SET @priceTempValue=@priceValue
		
		SELECT @priceTempValue
		SET @sql= 'DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
		EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
		select @priceValue= Round(' +  cast(@priceTempValue as varchar(50)) + @operator + cast(@price as varchar(50)) + ',@dig_price)'							
		EXEC sp_executesql @sql,N' @priceValue numeric(24,10) out',@priceValue out

		IF @priceValue<0 or @priceValue>999999
		BEGIN				
			ROLLBACK TRANSACTION  
        		CLOSE typeid_cursor  
 			DEALLOCATE typeid_cursor  
  			return -1
		END
		
	END
END



DECLARE @execsql varchar(500)
SET @execsql=''
--保存商品价格


IF Exists(Select * from PtypePrice where Ptypeid = @tempTypeid and priceTypeid = @priceTypeid)
BEGIN  
	--1.无公式的情况下
	IF @seltypeid=''
	BEGIN
		SET @execsql='Update PtypePrice SET Price ='+CAST(@price AS VARCHAR)+' WHERE priceTypeId='+char(39)+@pricetypeid+char(39)+' and ptypeid='+char(39)+@tempTypeid+char(39)  										
		exec(@execsql)		
		IF @@error <> 0 
		BEGIN
			--goto error
			ROLLBACK TRANSACTION  
        		CLOSE typeid_cursor  
 			DEALLOCATE typeid_cursor 
			--drop table #sourceprice
  			return -3
		END
		
		IF @pricetypeid='LSSJ1' --这边物价管理修改的 零售价（要同步更新商品表的零售价）
		BEGIN
			Update Ptype SET Retailprice=@price WHERE typeid =  @tempTypeid  and deleted = 0 
		END
		IF @@error <> 0 
		BEGIN
			--goto error
			ROLLBACK TRANSACTION  
        		CLOSE typeid_cursor  
 			DEALLOCATE typeid_cursor 
			--drop table #sourceprice
  			return -3
		END
	END
	ELSE
	BEGIN 
		 --在该商品的最近进价的基础操作 或 在其他用户自己添加的价格基础上,修改某个价格			
		SET @execsql='Update PtypePrice SET Price ='+CAST(@priceValue AS VARCHAR)+' WHERE priceTypeId='+char(39)+@pricetypeid +char(39)+' and ptypeid='+char(39)+@tempTypeid+char(39)  																	      				
		exec(@execsql)	
		IF @@error <> 0 
		BEGIN
			--goto error
			ROLLBACK TRANSACTION  
        		CLOSE typeid_cursor  
 			DEALLOCATE typeid_cursor 
			--drop table #sourceprice
  			return -3
		END
		IF @pricetypeid='LSSJ1' --这边物价管理修改的 零售价（要同步更新商品表的零售价）
		BEGIN
			Update Ptype SET Retailprice=@priceValue WHERE typeid =  @tempTypeid  and deleted = 0 
		END
		IF @@error <> 0 
		BEGIN
			--goto error
			ROLLBACK TRANSACTION  
        		CLOSE typeid_cursor  
 			DEALLOCATE typeid_cursor 
			--drop table #sourceprice
  			return -3
		END			
	END
END
ELSE
BEGIN  
	--1.无公式的情况下
	IF @seltypeid=''
	BEGIN	
		SET @execsql='Insert into PtypePrice(PriceTypeid,Ptypeid,Price) Values('+char(39)+@pricetypeid+char(39)+','+char(39)+@tempTypeid+char(39)+','+CAST(@price AS VARCHAR)+') '		
		exec(@execsql)						
		IF @@error <> 0 
		BEGIN
			--goto error
			ROLLBACK TRANSACTION  
        		CLOSE typeid_cursor  
 			DEALLOCATE typeid_cursor 
			--drop table #sourceprice
  			return -3
		END
		IF @pricetypeid='LSSJ1' --这边物价管理修改的 零售价（要同步更新商品表的零售价）
		BEGIN
			Update Ptype SET Retailprice=@price WHERE typeid =  @tempTypeid  and deleted = 0 
		END
		IF @@error <> 0 
		BEGIN
			--goto error
			ROLLBACK TRANSACTION  
        		CLOSE typeid_cursor  
 			DEALLOCATE typeid_cursor 
			--drop table #sourceprice
  			return -3
		END
	END
	ELSE
	BEGIN
		--在该商品的最近进价的基础操作 或 在其他用户自己添加的价格基础上,修改某个价格			
		SET @execsql='Insert into PtypePrice(PriceTypeid,Ptypeid,Price) Values('+char(39)+@pricetypeid+char(39)+','+char(39)+@tempTypeid+char(39)+','+CAST(@priceValue AS VARCHAR)+') '		
		exec(@execsql)		
		IF @@error <> 0 
		BEGIN
			--goto error
			ROLLBACK TRANSACTION  
        		CLOSE typeid_cursor  
 			DEALLOCATE typeid_cursor 
			--drop table #sourceprice
  			return -3
		END
		IF @pricetypeid='LSSJ1' --这边物价管理修改的 零售价（要同步更新商品表的零售价）
		BEGIN
			Update Ptype SET Retailprice=@priceValue WHERE typeid =  @tempTypeid  and deleted = 0 
		END
		IF @@error <> 0 
		BEGIN
			--goto error
			ROLLBACK TRANSACTION  
        		CLOSE typeid_cursor  
 			DEALLOCATE typeid_cursor 
			--drop table #sourceprice
  			return -3
		END		
	END
END


--写入历史表
insert into PriceModifyHis([date], etypeid, inputno, type, remark, ptypeid, PriceTypeid, oldprice, newprice)
			select @date, @etypeid, @inputno, 1, @remark, p.ptypeid, p.PriceTypeid, op.sourceprice, p.price
			from ptypeprice p inner join #sourceprice op
			on p.ptypeid = op.ptypeid
			where p.pricetypeid = @priceTypeid AND p.Ptypeid=@tempTypeid
IF @@error <> 0 
BEGIN
	--goto error
	ROLLBACK TRANSACTION  
	CLOSE typeid_cursor  
	DEALLOCATE typeid_cursor 
	--drop table #sourceprice
	return -3
END

DECLARE @UpdateTag INT    EXEC [dbo].[XW_GetUpdateTag] 'Ptype', @UpdateTag OUTPUT 	
Update ptype set  UpdateTag = @UpdateTag where typeid =  @tempTypeid and deleted = 0 

DECLARE @UpdateTagPrice INT    EXEC [dbo].[XW_GetUpdateTag] 'PtypePrice', @UpdateTagPrice OUTPUT 	
Update ptype set  UpdateTagPrice = @UpdateTagPrice where typeid =  @tempTypeid and deleted = 0 

IF @@error <> 0 
BEGIN
	--goto error
	ROLLBACK TRANSACTION  
	CLOSE typeid_cursor  
	DEALLOCATE typeid_cursor 
	--drop table #sourceprice
	return -3
END

--价格不能小于0
IF EXISTS(Select * from PtypePrice where  Ptypeid = @tempTypeid and priceTypeid = @priceTypeid and price<0 and (pricetypeid='LSSJ1' OR left(pricetypeid,5)='YSCGJ' OR left(pricetypeid,4)='YSSJ'))
BEGIN
	--goto error4	
	ROLLBACK TRANSACTION  
	CLOSE typeid_cursor  
	DEALLOCATE typeid_cursor 
	--drop table #sourceprice
	return -4
END	

--折扣 0-- 100
IF EXISTS(Select * from PtypePrice where  Ptypeid = @tempTypeid and priceTypeid = @priceTypeid and (price<0 or price>100) and (left(pricetypeid,4)='YSKL' OR left(pricetypeid,6)='YSCGZK' OR left(pricetypeid,4)='YSZK'))
BEGIN
	--goto error5	
	ROLLBACK TRANSACTION  
	CLOSE typeid_cursor  
	DEALLOCATE typeid_cursor 
	--drop table #sourceprice
	return -5
END	

IF (LEFT(@priceTypeid,6)='YSCGZK' OR  LEFT(@priceTypeid,4)='YSZK')--预设采购折扣,--预设折扣(如果用户输入的是100,PtypePrice不保存这样的数据)
BEGIN	
	Delete FROM  PtypePrice WHERE Ptypeid=@tempTypeid and priceTypeid=@priceTypeid AND (price=100	or price=0)	
END
IF @@error <> 0 
BEGIN	
	ROLLBACK TRANSACTION  
	CLOSE typeid_cursor  
	DEALLOCATE typeid_cursor 	
	return -5
END


IF (LEFT(@priceTypeid,4)='YSKL')--预设扣率(抽成率）,抽成率=0不保存这样的数据
BEGIN	
	Delete FROM  PtypePrice WHERE Ptypeid=@tempTypeid and priceTypeid=@priceTypeid AND price=0	
END
IF @@error <> 0 
BEGIN	
	ROLLBACK TRANSACTION  
	CLOSE typeid_cursor  
	DEALLOCATE typeid_cursor 	
	return -5
END

fetch next from typeid_cursor into @tempTypeid
end

CLOSE typeid_cursor
DEALLOCATE typeid_cursor
/*        
goto sucess

error1:
  drop table #sourceprice
 -- rollback tran 
  return -1

error:
  drop table #sourceprice
  --rollback tran 
  return -3
error4:
  drop table #sourceprice
  --rollback tran 
  return -4
error5:
  drop table #sourceprice
  --rollback tran 
  return -5
sucess:
  drop table #sourceprice
  --commit tran 
  return 0
*/

COMMIT TRANSACTION  
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].[FN_FZPtypeRWPrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FN_FZPtypeRWPrice]
GO


CREATE Proc FN_FZPtypeRWPrice
(
	@ptypeid 		VARCHAR(50),
	@priceTypeid		VARCHAR(50),  -- 要修改价格列名
	@price          	numeric(24,10), -- 调整值
	@date           	varchar(10),    -- 修改日期
	@etypeid		VARCHAR(50),    -- 经手人
	@inputno		VARCHAR(50),    -- 操作员
	@remark			varchar(200)   -- 备注
)
AS

begin tran ptypeprice

--第一步 生成原价格临时表(把要修改之前的价格记录下来)
if object_id('tempdb..#sourceprice') is not null Drop Table #SourcePrice
Create Table #sourceprice(ptypeid VARCHAR(50), sourceprice numeric(18,8))

IF (LEFT(@priceTypeid,6)='YSCGZK' OR  LEFT(@priceTypeid,4)='YSZK')--预设采购折扣,--预设折扣(如果用户输入的是0，含义等同于100)
BEGIN
	IF @price=0
	BEGIN
		SET @price=100
	END
END

IF (LEFT(@priceTypeid,6)='YSCGZK' OR  LEFT(@priceTypeid,4)='YSZK')--预设采购折扣,--预设折扣
BEGIN
	Insert into #sourceprice 
	select  p.typeid as ptypeid, isnull(pp.price, 100) sourceprice 
			from ptype p left join ptypeprice pp 
			on p.typeid = pp.ptypeid and pp.pricetypeid = @priceTypeid
			where p.typeid = @ptypeid  and p.deleted = 0
			order by ptypeid
END
ELSE
BEGIN
	Insert into #sourceprice
			select  p.typeid as ptypeid, isnull(pp.price, 0) sourceprice 
			from ptype p left join ptypeprice pp 
			on p.typeid = pp.ptypeid and pp.pricetypeid = @priceTypeid
			where p.typeid = @ptypeid and p.deleted = 0
			order by ptypeid
END



--保存商品价格
IF Exists(Select * from PtypePrice where Ptypeid = @Ptypeid and priceTypeid = @priceTypeid)
  Update PtypePrice set price= @price where Ptypeid = @Ptypeid and priceTypeid = @priceTypeid                     
ELSE
  Insert  PtypePrice(PriceTypeid, Ptypeid, Price) values(@priceTypeid,@Ptypeid,@price)
       
IF @@error <> 0
BEGIN
  goto  error
END

  Update ptype set retailprice = @price where Typeid = @Ptypeid and @priceTypeid ='LSSJ1'
IF @@error <> 0 
   BEGIN
	goto error
   END


--写入历史表
insert into PriceModifyHis([date], etypeid, inputno, type, remark, ptypeid, PriceTypeid, oldprice, newprice)
			select @date, @etypeid, @inputno, 0, @remark, p.ptypeid, p.PriceTypeid, op.sourceprice, p.price
			from ptypeprice p inner join #sourceprice op
			on p.ptypeid = op.ptypeid
			where p.pricetypeid = @priceTypeid AND p.Ptypeid=@ptypeid

IF @@error <> 0 
BEGIN	
	goto error
END


IF (LEFT(@priceTypeid,6)='YSCGZK' OR  LEFT(@priceTypeid,4)='YSZK')--预设采购折扣,--预设折扣(如果用户输入的是100,PtypePrice不保存这样的数据)
BEGIN	
	Delete FROM  PtypePrice WHERE Ptypeid=@Ptypeid and priceTypeid=@priceTypeid AND price=100	
END
IF @@error <> 0 
BEGIN	
	goto error
END

IF (LEFT(@priceTypeid,4)='YSKL')--预设扣率(抽成率）,抽成率=0不保存这样的数据
BEGIN	
	Delete FROM  PtypePrice WHERE Ptypeid=@Ptypeid and priceTypeid=@priceTypeid AND price=0	
END
IF @@error <> 0 
BEGIN	
	goto error
END

DECLARE @UpdateTag INT    EXEC [dbo].[XW_GetUpdateTag] 'Ptype', @UpdateTag OUTPUT 	
Update ptype set  UpdateTag = @UpdateTag where typeid =  @ptypeid and deleted = 0 

DECLARE @UpdateTagPrice INT    EXEC [dbo].[XW_GetUpdateTag] 'PtypePrice', @UpdateTagPrice OUTPUT 	
Update ptype set  UpdateTagPrice = @UpdateTagPrice where typeid =  @ptypeid and deleted = 0 

IF @@error <> 0 
BEGIN
	goto error
END
        
goto sucess

error:
  drop table #sourceprice
  rollback tran ptypeprice
  return -1 --alter by hww 2011年10月11日10:57:53 取消先前的注释 ，让其有返回值
sucess:
  drop table #sourceprice
  commit tran ptypeprice
  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].[BaseInfoBarGenerate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BaseInfoBarGenerate]
GO

CREATE PROCEDURE [dbo].[BaseInfoBarGenerate]
    (
		@typeid VARCHAR(50),
		@extraid INT = 0,
		@modes VARCHAR(2)
    )
AS 
SET NOCOUNT ON 
	DECLARE @maxid INT,@counter INT,@rptypeid VARCHAR(50),
	@rAttributeId1 INT,@rAttributeId2 INT,@rAttributeId3 INT,@rAttributeId4 INT,
	@rAttributeId5 INT,@rAttributeId6 INT,@rAttributeId7 INT,@rAttributeId8 INT,
	@rbtypeid VARCHAR(50),@rSizeIdList VARCHAR(1000),@rColorIdList VARCHAR(1000),
	@rFormatID VARCHAR(10),@rCSPZ INT,@rBarCode VARCHAR(100),@UpdateTag INT,@UpdateTagBar INT
	SET @maxid = 0
	SET @counter = 0
	
	IF @modes = 'C'
	BEGIN
		SELECT DISTINCT b.TypeID AS ptypeid,a.AttributeId1,a.AttributeId2,a.AttributeId3,
        a.AttributeId4,a.AttributeId5,a.AttributeId6,
        a.AttributeId7,a.AttributeId8,a.btypeid,b.SizeIdList,@typeid AS ColorIdList,
        b.FormatID,b.CSPZ,b.BarCode
        INTO #tepcolor
        FROM dbo.PtypeBar a,dbo.Ptype b
        WHERE a.PtypeID = b.TypeID 
        AND a.ColorID = CAST(@typeid AS INT)
        AND b.FormatID IN (SELECT DISTINCT CAST(PlanId AS VARCHAR) FROM dbo.BarCodeItem WHERE ItemNo = '02')
        
        SELECT ROW_NUMBER() OVER (ORDER BY PtypeID) AS rowid,* 
        INTO #tepcolordata
        FROM #tepcolor
		
		SELECT @maxid = MAX(rowid) FROM #tepcolordata
		
		WHILE @counter < @maxid
		BEGIN
			SELECT @rptypeid = ptypeid,@rAttributeId1 = AttributeId1,@rAttributeId2 = AttributeId2,@rAttributeId3 = AttributeId3,
			@rAttributeId4 = AttributeId4,@rAttributeId5 = AttributeId5,@rAttributeId6 = AttributeId6,@rAttributeId7 = AttributeId7,
			@rAttributeId8 = AttributeId8,@rBarCode = BarCode,@rbtypeid = btypeid,@rColorIdList = @typeid,@rSizeIdList = SizeIdList,
			@rCSPZ = CSPZ,@rFormatID = FormatID
			FROM #tepcolordata
			WHERE rowid = @counter+1
			
			EXEC dbo.GeneratePtypeBar @Formatid = @rFormatID, -- varchar(10)
			    @PtypeID = @rptypeid, -- varchar(50)
			    @cspz = @rCSPZ, -- int
			    @Barcode = @rBarCode, -- varchar(30)
			    @ColorIdList = @rColorIdList, -- varchar(1000)
			    @SizeIdList = @rSizeIdList, -- varchar(1000)
			    @AttributeId1 = @rAttributeId1, -- int
			    @AttributeId2 = @rAttributeId2, -- int
			    @AttributeId3 = @rAttributeId3, -- int
			    @AttributeId4 = @rAttributeId4, -- int
			    @AttributeId5 = @rAttributeId5, -- int
			    @AttributeId6 = @rAttributeId6, -- int
			    @AttributeId7 = @rAttributeId7, -- int
			    @AttributeId8 = @rAttributeId8, -- int
			    @Btypeid = @rbtypeid, -- varchar(50)
			    @mode = 'C' -- varchar(1)
			 
			 --基本信息有变动更新商品基本信息更新标识(POS用)
			 EXEC dbo.XW_GetUpdateTag 'Ptype', -- varchar(30)
			     @UpdateTag OUT-- int
			 UPDATE dbo.Ptype SET UpdateTag = @UpdateTag WHERE TypeID = @rptypeid
			 
			 EXEC dbo.XW_GetUpdateTag 'PtypeBar', -- varchar(30)
			     @UpdateTagBar OUT -- int
			 UPDATE dbo.Ptype SET UpdateTagBar = @UpdateTagBar WHERE TypeID = @rptypeid    
			 
			SET @counter = @counter + 1    
		END
		
		IF OBJECT_ID('tempdb..#tepcolor') IS NOT NULL 
        DROP TABLE #tepcolor
        IF OBJECT_ID('tempdb..#tepcolordata') IS NOT NULL 
        DROP TABLE #tepcolordata
	END
	
	IF @modes = 'S'
	BEGIN
		SELECT DISTINCT b.TypeID AS ptypeid,a.AttributeId1,a.AttributeId2,a.AttributeId3,
        a.AttributeId4,a.AttributeId5,a.AttributeId6,
        a.AttributeId7,a.AttributeId8,a.btypeid,@typeid AS SizeIdList,b.ColorIdList,
        b.FormatID,b.CSPZ,b.BarCode
        INTO #tepsize
        FROM dbo.PtypeBar a,dbo.Ptype b
        WHERE a.PtypeID = b.TypeID 
        AND a.SizeID = CAST(@typeid AS INT)
        AND b.FormatID IN (SELECT DISTINCT CAST(PlanId AS VARCHAR) FROM dbo.BarCodeItem WHERE ItemNo = '03')
        
        SELECT ROW_NUMBER() OVER (ORDER BY PtypeID) AS rowid,* 
        INTO #tepsizedata
        FROM #tepsize
		
		SELECT @maxid = MAX(rowid) FROM #tepsizedata
		
		WHILE @counter < @maxid
		BEGIN
			SELECT @rptypeid = ptypeid,@rAttributeId1 = AttributeId1,@rAttributeId2 = AttributeId2,@rAttributeId3 = AttributeId3,
			@rAttributeId4 = AttributeId4,@rAttributeId5 = AttributeId5,@rAttributeId6 = AttributeId6,@rAttributeId7 = AttributeId7,
			@rAttributeId8 = AttributeId8,@rBarCode = BarCode,@rbtypeid = btypeid,@rColorIdList = ColorIdList,@rSizeIdList = @typeid,
			@rCSPZ = CSPZ,@rFormatID = FormatID
			FROM #tepsizedata
			WHERE rowid = @counter+1
			
			EXEC dbo.GeneratePtypeBar @Formatid = @rFormatID, -- varchar(10)
			    @PtypeID = @rptypeid, -- varchar(50)
			    @cspz = @rCSPZ, -- int
			    @Barcode = @rBarCode, -- varchar(30)
			    @ColorIdList = @rColorIdList, -- varchar(1000)
			    @SizeIdList = @rSizeIdList, -- varchar(1000)
			    @AttributeId1 = @rAttributeId1, -- int
			    @AttributeId2 = @rAttributeId2, -- int
			    @AttributeId3 = @rAttributeId3, -- int
			    @AttributeId4 = @rAttributeId4, -- int
			    @AttributeId5 = @rAttributeId5, -- int
			    @AttributeId6 = @rAttributeId6, -- int
			    @AttributeId7 = @rAttributeId7, -- int
			    @AttributeId8 = @rAttributeId8, -- int
			    @Btypeid = @rbtypeid, -- varchar(50)
			    @mode = 'S' -- varchar(1)
			 
			 --基本信息有变动更新商品基本信息更新标识(POS用)
			 EXEC dbo.XW_GetUpdateTag 'Ptype', -- varchar(30)
			     @UpdateTag OUT -- int
			 UPDATE dbo.Ptype SET UpdateTag = @UpdateTag WHERE TypeID = @rptypeid   
			 
			 EXEC dbo.XW_GetUpdateTag 'PtypeBar', -- varchar(30)
			     @UpdateTagBar OUT -- int
			 UPDATE dbo.Ptype SET UpdateTagBar = @UpdateTagBar WHERE TypeID = @rptypeid    
			  
			SET @counter = @counter + 1    
		END
		
		IF OBJECT_ID('tempdb..#tepsize') IS NOT NULL 
        DROP TABLE #tepsize
        IF OBJECT_ID('tempdb..#tepsizedata') IS NOT NULL 
        DROP TABLE #tepsizedata
	END
	
	IF @modes = 'B'
	BEGIN
		SELECT DISTINCT b.TypeID AS ptypeid,a.AttributeId1,a.AttributeId2,a.AttributeId3,
        a.AttributeId4,a.AttributeId5,a.AttributeId6,
        a.AttributeId7,a.AttributeId8,@typeid AS btypeid,b.SizeIdList,b.ColorIdList,
        b.FormatID,b.CSPZ,b.BarCode
        INTO #tepbtype
        FROM dbo.PtypeBar a,dbo.Ptype b
        WHERE a.PtypeID = b.TypeID 
        AND a.btypeid = @typeid
        AND b.FormatID IN (SELECT DISTINCT CAST(PlanId AS VARCHAR) FROM dbo.BarCodeItem WHERE ItemNo = '12')
        
        SELECT ROW_NUMBER() OVER (ORDER BY PtypeID) AS rowid,*
        INTO #tepbtypedata
        FROM #tepbtype
		
		SELECT @maxid = MAX(rowid) FROM #tepbtypedata
		
		WHILE @counter < @maxid
		BEGIN
			SELECT @rptypeid = ptypeid,@rAttributeId1 = AttributeId1,@rAttributeId2 = AttributeId2,@rAttributeId3 = AttributeId3,
			@rAttributeId4 = AttributeId4,@rAttributeId5 = AttributeId5,@rAttributeId6 = AttributeId6,@rAttributeId7 = AttributeId7,
			@rAttributeId8 = AttributeId8,@rBarCode = BarCode,@rbtypeid = btypeid,@rColorIdList = ColorIdList,@rSizeIdList = SizeIdList,
			@rCSPZ = CSPZ,@rFormatID = FormatID
			FROM #tepbtypedata
			WHERE rowid = @counter+1
			
			EXEC dbo.GeneratePtypeBar @Formatid = @rFormatID, -- varchar(10)
			    @PtypeID = @rptypeid, -- varchar(50)
			    @cspz = @rCSPZ, -- int
			    @Barcode = @rBarCode, -- varchar(30)
			    @ColorIdList = @rColorIdList, -- varchar(1000)
			    @SizeIdList = @rSizeIdList, -- varchar(1000)
			    @AttributeId1 = @rAttributeId1, -- int
			    @AttributeId2 = @rAttributeId2, -- int
			    @AttributeId3 = @rAttributeId3, -- int
			    @AttributeId4 = @rAttributeId4, -- int
			    @AttributeId5 = @rAttributeId5, -- int
			    @AttributeId6 = @rAttributeId6, -- int
			    @AttributeId7 = @rAttributeId7, -- int
			    @AttributeId8 = @rAttributeId8, -- int
			    @Btypeid = @rbtypeid, -- varchar(50)
			    @mode = 'B' -- varchar(1)
			    
			 --基本信息有变动更新商品基本信息更新标识(POS用)
			 EXEC dbo.XW_GetUpdateTag 'Ptype', -- varchar(30)
			     @UpdateTag OUT -- int
			 UPDATE dbo.Ptype SET UpdateTag = @UpdateTag WHERE TypeID = @rptypeid   
			 
			 EXEC dbo.XW_GetUpdateTag 'PtypeBar', -- varchar(30)
			     @UpdateTagBar OUT -- int
			 UPDATE dbo.Ptype SET UpdateTagBar = @UpdateTagBar WHERE TypeID = @rptypeid    
			    
			SET @counter = @counter + 1    
		END
		
		IF OBJECT_ID('tempdb..#tepbtype') IS NOT NULL 
        DROP TABLE #tepbtype
        IF OBJECT_ID('tempdb..#tepbtypedata') IS NOT NULL 
        DROP TABLE #tepbtypedata
	END
	
	IF @modes = 'A'
	BEGIN
	    DECLARE @SqlCmd VARCHAR(8000)
	    SET @SqlCmd = 'SELECT DISTINCT b.TypeID as PtypeID,b.FormatID,b.CSPZ,b.BarCode,b.btypeid1 ,b.ColorIdList,b.SizeIdList,
				a.AttributeId1,
				a.AttributeId2,
				a.AttributeId3,
				a.AttributeId4,
				a.AttributeId5,
				a.AttributeId6,
				a.AttributeId7,
				a.AttributeId8
				into ##tepattribute
				FROM dbo.Ptype b,dbo.PtypeBar a
				WHERE a.PtypeID = b.TypeID
				AND a.AttributeId'+cast(@extraid AS varchar)+' = '+ @typeid +'
				AND b.FormatID IN (SELECT DISTINCT CAST(PlanId AS VARCHAR) FROM dbo.BarCodeItem WHERE ItemNo = '''+ 
                                        CASE WHEN @extraid=1 THEN '04' 
                                             WHEN @extraid=2 THEN '05'
                                             WHEN @extraid=3 THEN '06'
                                             WHEN @extraid=4 THEN '07'
                                             WHEN @extraid=5 THEN '08'
                                             WHEN @extraid=6 THEN '09'
                                             WHEN @extraid=7 THEN '10'
                                             WHEN @extraid=8 THEN '11'
                                             ELSE '00'
                                        END
                                         +''')'
	
		EXEC (@SqlCmd)
        
        SELECT ROW_NUMBER() OVER (ORDER BY PtypeID) AS rowid,*
        INTO ##tepattributedata
        FROM ##tepattribute
		
		SELECT @maxid = MAX(rowid) FROM ##tepattributedata
		
		WHILE @counter < @maxid
		BEGIN
			SELECT @rptypeid = ptypeid,@rAttributeId1 = AttributeId1,@rAttributeId2 = AttributeId2,@rAttributeId3 = AttributeId3,
			@rAttributeId4 = AttributeId4,@rAttributeId5 = AttributeId5,@rAttributeId6 = AttributeId6,@rAttributeId7 = AttributeId7,
			@rAttributeId8 = AttributeId8,@rBarCode = BarCode,@rbtypeid = @typeid,@rColorIdList = ColorIdList,@rSizeIdList = SizeIdList,
			@rCSPZ = CSPZ,@rFormatID = FormatID
			FROM ##tepattributedata
			WHERE rowid = @counter+1
			
			EXEC dbo.GeneratePtypeBar @Formatid = @rFormatID, -- varchar(10)
			    @PtypeID = @rptypeid, -- varchar(50)
			    @cspz = @rCSPZ, -- int
			    @Barcode = @rBarCode, -- varchar(30)
			    @ColorIdList = @rColorIdList, -- varchar(1000)
			    @SizeIdList = @rSizeIdList, -- varchar(1000)
			    @AttributeId1 = @rAttributeId1, -- int
			    @AttributeId2 = @rAttributeId2, -- int
			    @AttributeId3 = @rAttributeId3, -- int
			    @AttributeId4 = @rAttributeId4, -- int
			    @AttributeId5 = @rAttributeId5, -- int
			    @AttributeId6 = @rAttributeId6, -- int
			    @AttributeId7 = @rAttributeId7, -- int
			    @AttributeId8 = @rAttributeId8, -- int
			    @Btypeid = @rbtypeid, -- varchar(50)
			    @mode = 'A', -- varchar(1)
			    @AttributeFlagId = @extraid
			 
			 --基本信息有变动更新商品基本信息更新标识(POS用)
			 EXEC dbo.XW_GetUpdateTag 'Ptype', -- varchar(30)
			     @UpdateTag OUT -- int
			 UPDATE dbo.Ptype SET UpdateTag = @UpdateTag WHERE TypeID = @rptypeid    
			 
			 EXEC dbo.XW_GetUpdateTag 'PtypeBar', -- varchar(30)
			     @UpdateTagBar OUT -- int
			 UPDATE dbo.Ptype SET UpdateTagBar = @UpdateTagBar WHERE TypeID = @rptypeid    
			
			SET @counter = @counter + 1    
		END
		
		IF OBJECT_ID('tempdb..##tepattribute') IS NOT NULL 
        DROP TABLE ##tepattribute
        IF OBJECT_ID('tempdb..##tepattributedata') IS NOT NULL 
        DROP TABLE ##tepattributedata
	END
	
SET NOCOUNT OFF

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].[FzInsertP]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FzInsertP]
GO






--  ********************************************************************************************
--  ||                                                                                        
--  ||   过程名称： FzInsertP                                   
--  ||   过程功能：添加基本信息--仓库
--  ||=========================================================================================
--  ||   参数说明：  参数名称         类型            意义                     输入输出
--  ||            -----------------------------------------------------------------------------
--  ||  	@Parid 		varchar(50),                                             --父亲ID号1
--  ||  	@dbname        	varchar(30),                                             --操作的数据库表名2
--  ||  	@FullName 	varchar(66),                                             --商品全名3
--  ||  	@Name		varchar(30),                                             --商品简名4
--  ||  	@UserCode 	varchar(26),                                             --用户编码5
--  ||  	@Standard 	varchar(20),                                             --商品规格6
--  ||  	@Type	 	varchar(20),                                             --商品类型7
--  ||  	@Area	 	varchar(30),                                             --商品产地8
--  ||  	@Unit1 		varchar(8),                                              --商品单位1  9
--  ||  	@Unit2 		varchar(8),                                              --商品单位2  10
--  ||  	@UnitRate1 	numeric(24,10),                                          --单位关系1  11
--  ||  	@UnitRate2 	numeric(24,10),                                          --单位关系2  12
--  ||  	@preprice1 	numeric(24,10),                                          --预设售价1  13
--  ||  	@preprice2 	numeric(24,10),                                          --预设售价2  14
--  ||  	@preprice3 	numeric(24,10),                                          --预设售价3  15
--  ||  	@preprice4 	numeric(24,10),                                          --预设售价4  16
--  ||	        @retailprice    numeric(24,10),		  			         --零售价
--  ||	        @minprice       numeric(24,10),					         --最低售价
--  ||  	@LifeMonth 	smallint,                                                --保质期月17
--  ||  	@LifeDay 	smallint,                                                --保质期天18
--  ||  	@CostMode	smallint,                                                --成本算法19
--  ||  	@Comment 	varchar(256),                                            --备注20
--  ||  	@namepy	        varchar(60),                                                     --全名简拼21
--  ||  	@Barcode	varchar(30),                                             --商品条码22
--  ||  	@sizegroupid    int,                                                   --尺码组23
--  ||  	@colorgroupid   int,                                                    --颜色组24
--  ||  	@breakwarn      numeric(24,10),                                         --断码报警数25
--  ||  	@Formatid       varchar(10),                                         --条码格式26
--  ||  	@cspz           int,                                                --颜色尺码配置
--  ||  	@backRec        int  output,						 --
--  ||  	@material	int,                                                  --面料
--  ||  	@season         int,                                                   --季节
--  ||  	@category       int,	                                                --品牌
--  ||  	 @year          int,		                                         --年度
--  ||               -- @SPPIC  image,		                                       -- 商品图片
--  ||  	 @trade         bit,                                              --可否换货0：不能换货，1：可以换货
--  ||  	 @stop          bit                                               -- 是否停用
--  ||         @discount        int 						         折扣0
--  ||        @discount1        int                                                      折扣1
--  ||        @discount2	int							 折扣2
--  ||        @discount3	int							 折扣3
--  ||=========================================================================================   
--  ||    返回值： 值               说明               
--  ||                   -1                  -- 数据库操作失败！
--  ||                   -2                -- 此记录已经过账，不能再分类！
--  ||                   -3                  -- 父亲ID号不存在！
--  ||                   -4                -- 系统行不允许修改！
--  ||                   -6                 有相同条码的记录存在
--  ||	            -7                插入的颜色、尺码的条码失败
--  ||=========================================================================================

/*
cqhua 2011-8-29
尺码组改变
*/
CREATE    PROCEDURE FzInsertP
    (
      @Parid VARCHAR(50) ,                                             --父亲ID号1
      @dbname VARCHAR(30) ,                                             --操作的数据库表名2
      @FullName VARCHAR(66) ,                                             --商品全名3
      @Name VARCHAR(30) ,                                             --商品简名4
      @UserCode VARCHAR(26) ,                                             --用户编码5
      @Standard VARCHAR(20) ,                                             --商品规格6
      @Type VARCHAR(20) ,                                             --商品类型7
      @Area VARCHAR(30) ,                                             --商品产地8
      @Unit1 VARCHAR(8) ,                                               --商品单位1  9
      @Unit2 VARCHAR(8) ,                                               --商品单位2  10
      @UnitRate1 NUMERIC(24, 10) = 1,                                        --单位关系1  11
      @UnitRate2 NUMERIC(24, 10) = 1,                                        --单位关系2  12
      @preprice1 NUMERIC(24, 10) ,                                        --预设售价1  13
      @preprice2 NUMERIC(24, 10) ,                                        --预设售价2  14
      @preprice3 NUMERIC(24, 10) ,                                        --预设售价3  15
      @preprice4 NUMERIC(24, 10) ,                                        --预设售价4  16
      @retailprice NUMERIC(24, 10) ,			            --零售价
      @minprice NUMERIC(24, 10) ,				--最低售价
      @LifeMonth SMALLINT ,                                                    --保质期月17
      @LifeDay SMALLINT ,                                                    --保质期天18
      @CostMode INT ,                                                           --成本算法19
      @Comment VARCHAR(256) ,                                           --备注20
      @namepy VARCHAR(100) ,                                             --全名简拼21
      @Barcode VARCHAR(30) ,                                             --商品条码22
      @sizegroupid INT ,                                                           --尺码组23
      @colorgroupid INT ,                                                           --颜色组24
      @breakwarn NUMERIC(24, 10) ,                                       --断码报警数25
      @Formatid VARCHAR(10) ,                                             --条码格式26
      @cspz INT ,                                                            --颜色尺码配置
      @backRec INT OUTPUT ,--
      @material INT ,                                                            --面料
      @season INT ,                                                           --季节
      @category INT ,                                                           --品牌
      @year INT ,                                                            --年度
               -- @SPPIC image,                                                      -- 商品图片
      @trade BIT ,                                                            --可否换货0：不能换货，1：可以换货
      @stop BIT ,                                                                     --是否停用  0：没有停用，1：已经停用
      @discount NUMERIC(24, 10) ,
      @discount1 NUMERIC(24, 10) ,
      @discount2 NUMERIC(24, 10) ,
      @discount3 NUMERIC(24, 10) ,
      @newtypeid VARCHAR(50) OUTPUT ,
      @StopDate VARCHAR(10) = '' ,
      @ColorIdList VARCHAR(1000) = '' ,
      @SizeIdList VARCHAR(1000) = '' ,
      @iPa1 INT ,
      @iPa2 INT ,
      @iPa3 INT ,
      @iPa4 INT ,
      @Issuedate VARCHAR(10) = '' ,
      @btypeid VARCHAR(50) = '' ,
      @changerule INT ,
      @Custom1 VARCHAR(255) = '' ,
      @Custom2 VARCHAR(255) = '' ,
      @Custom3 VARCHAR(255) = '' ,
      @Custom4 VARCHAR(255) = '' ,
      @Custom5 VARCHAR(255) = '' ,
      @singleunit INT = 0,
      @BuyUnit INT = 1,
      @SaleUnit INT = 1,
      @PhUnit INT =1,
      @GoodsUnit INT = 1,
      @AttributeId1 INT = 0,                      --与辅助属性类型对应
	  @AttributeId2 INT = 0,
      @AttributeId3 INT = 0,
	  @AttributeId4 INT = 0,
	  @AttributeId5 INT = 0,
	  @AttributeId6 INT = 0,
	  @AttributeId7 INT = 0,
	  @AttributeId8 INT = 0
    )
AS 
    DECLARE @nReturntype INT
    DECLARE @EtypeId_1 VARCHAR(50)
    DECLARE @nSoncount INT
    DECLARE @nSonnum INT
    DECLARE @leveal SMALLINT
    DECLARE @ParRec INT
    DECLARE @BarConID INT
    DECLARE @Stats1 INT
    DECLARE @Stats2 INT
    DECLARE @UpdateTag INT,@UpdateTagAttribute INT,@UpdateTagBar INT,@UpdateTagPrice INT
-- 取得ID号
    EXEC @nReturntype= FzcreateId @ParId, @dbname, @EtypeId_1 OUT,
        @nSonnum OUT, @nSoncount OUT, @ParRec OUT
    IF @nReturntype = -101 
        GOTO error111 --parid不存在
    IF @nReturntype = -102 
        GOTO error112--有相关数据存在
    IF @nReturntype = -108 
        GOTO error108--有相关数据存在
    IF @nReturntype = -109 
        GOTO error109--有相关数据存在
    IF @nReturntype = -126 
        GOTO error126--有相关数据存在
    IF @nReturntype = -103 
        GOTO error113--未取得儿子编码
    IF @nReturntype = -133 
        GOTO error133--未取得儿子编码
    IF @nReturntype = -138 
        GOTO error138--未取得儿子编码
    IF @nReturntype = -150 
        GOTO error150--未取得儿子编码
    IF @nReturntype = -153 
    	GOTO error153--未取得儿子编码
    IF @nReturntype = -155
    	GOTO error155--未取得儿子编码
    IF @nReturntype = -156
	GOTO error156--未取得儿子编码
    IF @nReturntype = -157
	GOTO error157--未取得儿子编码  商品已经停用
    IF @nReturntype = -158
	GOTO error158--未取得儿子编码  商品已经停用


    IF @Issuedate = '' 
        SET @Issuedate = CONVERT(CHAR(10), GETDATE(), 121)
        
    IF @Parid <> ''    --分类新增的情况下清除父类商品的辅助单位
     BEGIN
      	UPDATE dbo.Ptype SET Unit2 = '' WHERE TypeID = @Parid AND Unit2 <> ''
     END    
        
-- 查找编号和全名不能完全相同
--读取系统配置表中的编号、全名配置规则
    SELECT  @Stats1 = stats
    FROM    syscon
    WHERE   [order] = 81
    SELECT  @Stats2 = stats
    FROM    syscon
    WHERE   [order] = 82
    IF @Stats1 = 1 
        IF EXISTS ( SELECT  [typeid]
                    FROM    ptype
                    WHERE   [typeId] = @EtypeId_1
                            OR ( fullname = @fullname
                                 AND [deleted] <> 1
                               ) ) 
            GOTO error114
    IF @Stats2 = 1 
        IF EXISTS ( SELECT  [typeid]
                    FROM    ptype
                    WHERE   [typeId] = @EtypeId_1
                            OR ( usercode = @usercode
                                 AND [deleted] <> 1
                               ) ) 
            GOTO error115
    IF @Stats1 = 0
        AND @Stats2 = 0 
        IF EXISTS ( SELECT  [typeid]
                    FROM    ptype
                    WHERE   [typeId] = @EtypeId_1
                            OR ( fullname = @fullname
                                 AND usercode = @usercode
                                 AND [deleted] <> 1
                               ) ) 
            GOTO error117
--条码相同
    IF ( LEN(RTRIM(LTRIM(@Barcode))) > 0 ) 
        BEGIN  
            IF EXISTS ( SELECT  [typeid]
                        FROM    ptype
                        WHERE   [typeId] = @EtypeId_1
                                OR ( Barcode = @Barcode )
                                AND [deleted] <> 1 ) 
                GOTO error200
        END
    IF EXISTS ( SELECT  getid
                FROM    dbo.GetIdListTable(@ColorIdList)
                WHERE   getid NOT IN ( SELECT   colorid
                                       FROM     color ) ) 
        GOTO error1117
    IF EXISTS ( SELECT  getid
                FROM    dbo.GetIdListTable(@SizeIdList)
                WHERE   getid NOT IN ( SELECT   sizeid
                                       FROM     size ) ) 
        GOTO error1118

--向表中写入数据
    BEGIN TRAN InsertP
    SELECT  @leveal = [leveal]
    FROM    ptype
    WHERE   [Typeid] = @Parid
    SELECT  @leveal = @leveal + 1

    EXEC [dbo].[XW_GetUpdateTag] 'Ptype', @UpdateTag OUTPUT
   EXEC [dbo].[XW_GetUpdateTag] 'PtypeAttribute', @UpdateTagAttribute OUTPUT
   EXEC [dbo].[XW_GetUpdateTag] 'PtypeBar', @UpdateTagBar OUTPUT
   EXEC [dbo].[XW_GetUpdateTag] 'PtypePrice', @UpdateTagPrice OUTPUT 

	IF @SizeIdList ='1'
		SET @sizegroupid =1
    INSERT  INTO [ptype]
            ( [typeId] ,
              [Parid] ,
              [leveal] ,
              [soncount] ,
              [sonnum] ,
              [FullName] ,
              [Name] ,
              [UserCode] ,
              [Standard] ,
              [Type] ,
              [Area] ,
              [Unit1] ,
              [Unit2] ,
              [UnitRate1] ,
              [UnitRate2] ,
              retailprice ,
              [costmode] ,
              [Comment] ,
              [namepy] ,
              [Barcode] ,
              breakwarn ,
              formatid ,
              cspz ,
              trade ,
              stop ,
              StopDate ,
              issueDate ,
              ColorIdList ,
              SizeIdList ,
              updateTag ,
              UpdateTagAttribute,
              UpdateTagBar,
              UpdateTagPrice,
              btypeid1 ,
              changerule ,
              PCustom1 ,
              PCustom2 ,
              PCustom3 ,
              PCustom4 ,
              PCustom5,
			  sizegroupid,
			  singleunit,
              BuyUnit,
              SaleUnit,
              PhUnit,
              GoodsUnit,
              MininumPrice
            )
    VALUES  ( @EtypeId_1 ,
              @Parid ,
              @leveal ,
              0 ,
              0 ,
              @FullName ,
              @Name ,
              @UserCode ,
              @Standard ,
              @Type ,
              @Area ,
              @Unit1 ,
              @Unit2 ,
              @UnitRate1 ,
              @UnitRate2 ,
              @retailprice ,
              @CostMode ,
              @Comment ,
              @namepy ,
              @Barcode ,
              @breakwarn ,
              @formatid ,
              @cspz ,
              @trade ,
              @stop ,
              @StopDate ,
              @Issuedate ,
              @ColorIdList ,
              @SizeIdList ,
              @UpdateTag ,
              @UpdateTagAttribute,
              @UpdateTagBar,
              @UpdateTagPrice,
              @btypeid ,
              @changerule ,
              @Custom1 ,
              @Custom2 ,
              @Custom3 ,
              @Custom4 ,
              @Custom5,
			  @sizegroupid,
		      @singleunit,
              @BuyUnit,
              @SaleUnit,
              @PhUnit,
              @GoodsUnit,
              @minprice
            )
    IF @@rowcount = 0 --写数据失败回滚事务
        BEGIN
            ROLLBACK TRAN InsertP 
            RETURN -1
        END 
    ELSE --写数据成功则更新儿子计数（现有、和曾有的儿子数）
        BEGIN
            DELETE  ptypeColor
            WHERE   ptypeid = @EtypeId_1
                  
            IF @@error <> 0 --写数据失败回滚事务
                BEGIN
                    ROLLBACK TRAN InsertP 
                    RETURN -1
                END  
            INSERT  INTO PtypeColor
                    ( Ptypeid ,
                      Colorid
                    )
                    SELECT  @EtypeId_1 ,
                            getid
                    FROM    dbo.GetIdListTable(@ColorIdList)
            IF @@error <> 0 --写数据失败回滚事务
                BEGIN
                    ROLLBACK TRAN InsertP 
                    RETURN -1
                END  

            DELETE  ptypeSize
            WHERE   ptypeid = @EtypeId_1
                  
            IF @@error <> 0 --写数据失败回滚事务
                BEGIN
                    ROLLBACK TRAN InsertP 
                    RETURN -1
                END  
            INSERT  INTO ptypeSize
                    ( Ptypeid ,
                      Sizeid
                    )
                    SELECT  @EtypeId_1 ,
                            getid
                    FROM    dbo.GetIdListTable(@SizeIdList)
            IF @@error <> 0 --写数据失败回滚事务
                BEGIN
                    ROLLBACK TRAN InsertP 
                    RETURN -1
                END                       
             
            UPDATE  [ptype]
            SET     [sonnum] = @nSonnum + 1 ,
                    [soncount] = @nSoncount + 1 ,
                    UpdateTag = CASE WHEN SonNum>0 THEN UpdateTag ELSE @UpdateTag END,
                    UpdateTagAttribute = CASE WHEN SonNum>0 THEN UpdateTagAttribute ELSE @UpdateTagAttribute END,
                    UpdateTagBar = CASE WHEN SonNum>0 THEN UpdateTagBar ELSE @UpdateTagBar END,
                    UpdateTagPrice = CASE WHEN SonNum>0 THEN UpdateTagPrice ELSE @UpdateTagPrice END
            WHERE   [typeid] = @Parid
            SELECT  @backRec = @@identity 
        END
    IF EXISTS ( SELECT  Ptypeid
                FROM    Ptypebar
                WHERE   Ptypeid = @Parid ) 
        DELETE  ptypebar
        WHERE   Ptypeid = @Parid
    IF ( LEN(@Barcode) > 0 ) 
        BEGIN  
			EXEC GeneratePtypeBar @Formatid,@EtypeId_1,@cspz,@Barcode,@ColorIdList,@SizeIdList,@AttributeId1,@AttributeId2,@AttributeId3,@AttributeId4,@AttributeId5,@AttributeId6,@AttributeId7,@AttributeId8,@Btypeid
        END

--设置系统数据表中的条码格式     
    IF @formatid = '1' 
        SELECT  @BarConID = 1
    ELSE 
        IF @formatid = '2' 
            SELECT  @BarConID = 0
        ELSE 
            SELECT  @BarConID = 2
    UPDATE  sysdata
    SET     subvalue = @BarConID
    WHERE   subno = 25

	delete from PriceModifyHis where PtypeId = @Parid --删除父类商品价格修改记录

	--商品颜色不包含在已有的颜色组中，新增颜色组
	--IF NOT EXISTS(SELECT * FROM dbo.SysData WHERE SubName = 'ProcTypeName' AND SubValue = 'FZCS') AND NOT EXISTS (select * FROM  (select distinct replace(','+dbo.GetColoridlist(colorgroupid)+',',',,',',') as colorIdlistOrder from colorGroupRelation) X WHERE dbo.SizeListInclude(colorIdlistOrder,@colorIdlist)=1 )
	--BEGIN
	--	INSERT INTO colorGroup(name,remark,sysrow,[order])  select (select '系统颜色组'+(select Convert(varchar(10),isnull(max(colorGroupid),1)) from colorGroup)) as name,'系统升级自动生成',0,10000
	--	INSERT INTO colorGroupRelation(colorGroupID,colorid,rec,[order]) select @@identity,getid,0,iorder from  GetIdListTable(@colorIdlist)
	--END

	--UPDATE Ptype SET ColorGroupID = 1 WHERE   typeid=@EtypeId_1 AND ColorGroupID=0 AND @colorIdlist ='1'
	
	--UPDATE Ptype SET ColorGroupID = S.Colorgroupid
	--FROM Ptype p INNER JOIN  (select distinct Colorgroupid,replace(','+dbo.GetColoridlist(Colorgroupid)+',',',,',',') as colorIdlistOrder from ColorGroupRelation) S 
	--ON dbo.SizeListInclude(S.ColorIdlistOrder,Coloridlist)=1 
	--WHERE P.typeid=@EtypeId_1 AND P.ColorGroupID=0


      
--以上操作完全通过则提交事务
    COMMIT TRAN InsertP
    GOTO succee
    succee:
    SELECT  @newtypeid = @EtypeId_1
    RETURN  0--增加记录成功


    error108:
    RETURN -108 --盘点使用过

    error109:
    RETURN -109 --订单使用过
    error126:
    RETURN -126 --商品对照码存在，不能分类
    error111:
      
    RETURN -1--输入的父亲ID 号不存在
    error112:
   
    RETURN -2--有相关数据存在
    error113:
     
    RETURN -3--未取的儿子编码
    error114:
 
    RETURN -4--有相同的全名存在
    error200:
   
    RETURN -6--有相同条码的数据存在
    error115:
    RETURN -5--有相同的编码存在
    error117:
    RETURN -7--有相同编码和全名的数据存在

    error1117:
    RETURN -17--颜色不存存在
    error1118:
    RETURN -18--尺码不存存在

    error133:
    RETURN -133--促销使用过
    error138:
    RETURN -138--物价管理使用过，不能分类
    error150:
    RETURN -150--POS小票使用过，不能分类
    
	error153:
	return -153--智能配货使用过，不能分类

	error155:
	RETURN -155  --VIP设置使用过，不能分类
	error156:
	RETURN -156  --退换货调整单使用过，不能分类
	error157:
	RETURN -157  --商品已经停用，不能分类
	error158:
	RETURN -158  --智能配货使用过，不能分类
    
    errorcur:
    BEGIN
        CLOSE cur_color 
        DEALLOCATE cur_color 
        CLOSE cur_size 
        DEALLOCATE cur_size
        ROLLBACK TRAN InsertP 
        RETURN -7      
    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].[FZSearchLoadVchdetail]')
                  AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
  DROP PROCEDURE [dbo].[FZSearchLoadVchdetail]

GO

--  ******************************************************************************************
--  ||                                                                                        
--  ||   SearchLoadVchdetail                                     
--  ||==========================================================================================
CREATE PROCEDURE FZSearchLoadVchdetail (
  @LoadVchType  INT,
  @OrderVchList VARCHAR(8000),
  @PtypeId      VARCHAR(50),
  @ColorId      INT
)
AS
    DECLARE @szSql VARCHAR(8000)

    SET @OrderVchList=Rtrim(@OrderVchList)

    IF @LoadVchType IN (7, 8, 221, 223,
                        211, 214) -- 调订单
      BEGIN
          IF EXISTS(SELECT 1
                    FROM   sysdata
                    WHERE  subname = 'ProcTypeName'
                           AND subvalue = 'FZBS')
            BEGIN
                SELECT p.TypeID,
                       p.UserCode,
                       p.FullName,
                       p.costmode,
                       o.Vchtype,
                       d.ifsupply,
                       o.btypeid AS btypeid,
                       o.number AS number,
                       o.btypeid AS Cusid,
                       o.BranchId AS rebcid, 
                       CASE
                         WHEN EXISTS(SELECT 1
                                     FROM   BtypeSupply bs
                                     WHERE  bs.btypeid = CASE
                                                           WHEN @LoadVchType = 211 THEN d.KtypeId
                                                           ELSE d.Btypeid
                                                         END
                                            AND bs.ptypeid = d.ptypeid
                                            AND bs.ColorId = d.ColorId) THEN 1
                         ELSE 0
                       END                           AS ReStock,
                       d.kTypeID,
                       d.btypeid,
                       d.Qty,
                       d.discount,
                       d.costprice,
                       d.price,
                       d.Tax_Total,
                       d.tax,
                       d.Vchcode,
                       d.dlyorder,
                       p.retailprice,
                       k.fullname                    AS kfullname,
                       b.fullname                    AS bfullname,
                       c.Name                        AS ColorName,
                       d.toqty,
                       --d.qty-d.toqty as DelayQty,
                       (SELECT sum(f.qty - f.toqty)
                        FROM   bakdlyorderdetail f
                        WHERE  f.dlyorder = d.dlyorder
                               AND f.qty >= f.toqty) AS DelayQty,
                       o.todate,
                       d.CustValue1,
                       d.CustValue2,
                       d.CustValue3,
                       d.CustValue4,
                       d.CustValue5,
                       d.CustValue6
                FROM   ptype p
                       INNER JOIN BakDlyOrder d ON p.typeId = d.PtypeId
                       INNER JOIN GetVchtypeOrVchcode(@OrderVchList, 0) V ON d.Vchcode = V.VchtypeOrVchcode
                       INNER JOIN DlyndxOrder o ON d.Vchcode = o.Vchcode
                       LEFT JOIN btype b ON b.typeid = d.btypeid
                       LEFT JOIN stock k ON d.ktypeid = k.typeid
                       LEFT JOIN color c ON d.colorid = c.colorid
                WHERE  d.colorid = CASE
                                     WHEN @ColorId = 0 THEN d.colorid
                                     ELSE @ColorId
                                   END
                       AND p.typeId LIKE CASE @PtypeId
                                           WHEN '' THEN p.typeId
                                           ELSE @PtypeId
                                         END + '%'
                --           and d.toqty<d.qty
                ORDER  BY d.DlyOrder
            END
          ELSE
            BEGIN
                SELECT p.TypeID,
                       p.UserCode,
                       p.FullName,
                       p.costmode,
                       o.Vchtype,
                       d.ifsupply,
                       CASE
                         WHEN EXISTS(SELECT 1
                                     FROM   BtypeSupply bs
                                     WHERE  bs.btypeid = CASE
                                                           WHEN @LoadVchType = 211 THEN d.KtypeId
                                                           ELSE d.Btypeid
                                                         END
                                            AND bs.ptypeid = d.ptypeid
                                            AND bs.ColorId = d.ColorId) THEN 1
                         ELSE 0
                       END             AS ReStock,
                       d.kTypeID,
                       d.btypeid,
                       d.Qty,
                       d.discount,
                       d.costprice,
                       d.price,
                       d.Tax_Total,
                       d.tax,
                       d.Vchcode,
                       d.dlyorder,
                       p.retailprice,
                       k.fullname      AS kfullname,
                       b.fullname      AS bfullname,
                       c.Name          AS ColorName,
                       d.toqty,
                       d.qty - d.toqty AS DelayQty,
                       o.todate,
                       d.CustValue1,
                       d.CustValue2,
                       d.CustValue3,
                       d.CustValue4,
                       d.CustValue5,
                       d.CustValue6,
                       d.isover
                FROM   ptype p
                       INNER JOIN BakDlyOrder d ON p.typeId = d.PtypeId
                       INNER JOIN GetVchtypeOrVchcode(@OrderVchList, 0) V ON d.Vchcode = V.VchtypeOrVchcode
                       INNER JOIN DlyndxOrder o ON d.Vchcode = o.Vchcode
                       LEFT JOIN btype b ON b.typeid = d.btypeid
                       LEFT JOIN stock k ON d.ktypeid = k.typeid
                       LEFT JOIN color c ON d.colorid = c.colorid
                WHERE  d.colorid = CASE
                                     WHEN @ColorId = 0 THEN d.colorid
                                     ELSE @ColorId
                                   END
                       AND p.typeId LIKE CASE @PtypeId
                                           WHEN '' THEN p.typeId
                                           ELSE @PtypeId
                                         END + '%'
                --           and d.toqty<d.qty
                ORDER  BY d.DlyOrder
            END
      END
    ELSE
      BEGIN
          SELECT p.TypeID,
                 p.UserCode,
                 p.FullName,
                 p.costmode,
                 o.Vchtype,
                 d.ifsupply,
                 0          AS ReStock,
                 d.kTypeID,
                 d.btypeid,
                 d.Qty,
                 d.discount,
                 d.costprice,
                 d.price,
                 d.Tax_Total,
                 d.tax,
                 d.Vchcode,
                 d.dlyorder,
                 k.fullname AS kfullname,
                 b.fullname AS bfullname,
                 c.Name     AS ColorName,
                 0          AS toqty,
                 0          AS DelayQty,
                 o.flag     AS CarryFlag,
                 d.CustValue1,
                 d.CustValue2,
                 d.CustValue3,
                 d.CustValue4,
                 d.CustValue5,
                 d.CustValue6
          FROM   ptype p
                 INNER JOIN dlydata d ON p.typeId = d.PtypeId
                 INNER JOIN GetVchtypeOrVchcode(@OrderVchList, 0) V ON d.Vchcode = CAST(V.VchtypeOrVchcode AS INT)
                 INNER JOIN dlyndx o ON d.Vchcode = o.Vchcode
                 LEFT JOIN btype b ON b.typeid = d.btypeid
                 INNER JOIN stock k ON k.typeid = d.ktypeid
                 LEFT JOIN color c ON d.colorid = c.colorid
          WHERE  p.typeId LIKE CASE @PtypeId
                                 WHEN '' THEN p.typeId
                                 ELSE @PtypeId
                               END + '%'
                 AND d.colorid = CASE
                                   WHEN CONVERT(VARCHAR(10), @ColorId) = 0 THEN d.colorid
                                   ELSE CONVERT(VARCHAR(10), @ColorId)
                                 END
                 AND d.usedtype = 1
                 AND o.Vchtype = CONVERT(NUMERIC(4, 0), @LoadVchType)
          ORDER  BY d.DlyOrder
      END

GO

SET QUOTED_IDENTIFIER OFF

GO

SET ANSI_NULLS ON

GO 
/******************************************20130903********************************************/

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO
 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BranchPHApply]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROC BranchPHApply
 GO
CREATE PROCEDURE BranchPHApply  
    ( 
		@date_s                VARCHAR(20),
		@date_e                VARCHAR(20),
		@bctypeid              VARCHAR(50),
		@ktypeid               VARCHAR(50),
		@ptypeid               VARCHAR(50),
		@pcrec                 INT,
		@psrec                 INT,
		@assisttypevalue       INT,
		@saletype              VARCHAR(20),
		@publish_s             VARCHAR(20),
		@publish_e             VARCHAR(20),
		@operatorID            VARCHAR(50)
    )  
AS  
BEGIN
    DECLARE @vchtypes VARCHAR(1000)
    SET @vchtypes = ''
    IF @saletype = '0'
    BEGIN
    SET @vchtypes = '11,24,45';
    END
    ELSE
    IF @saletype = '1'
    BEGIN
    SET @vchtypes = '12,100'; 
    END
    ELSE
    BEGIN
    SET @vchtypes = '11,24,45,12,100'; 
    END
    
    IF object_id('tempdb..#ptypetmp') is not null   
    drop table #ptypetmp
    SELECT TypeID AS ptypeid,IssueDate
    INTO #ptypetmp
    FROM dbo.FN_GetPowerRangePList(@operatorID,@ptypeid)
    
    IF object_id('tempdb..#ktypetmp') is not null   
    drop table #ktypetmp
    SELECT KtypeId
    INTO #ktypetmp
    FROM dbo.FN_GetStockListOfBranch(@operatorID,@bctypeid,@ktypeid)
    
    IF object_id('tempdb..#data') is not null   
    drop table #data
	SELECT a.PtypeId,b.SizeID,b.ColorID,SUM(-b.Qty) AS qty
	INTO #data
	FROM dbo.DlyData a INNER JOIN dbo.DlyDataDetail b ON a.Vchcode = b.Vchcode AND a.DlyOrder = b.DlyOrder
	WHERE a.[Date] BETWEEN @date_s AND @date_e
	AND a.RedOld = 'F'
	AND b.ColorID = CASE WHEN @pcrec<>-1 THEN @pcrec ELSE b.ColorID END
	AND b.SizeID = CASE WHEN @psrec<>-1 THEN @psrec ELSE b.SizeID END
	AND EXISTS(SELECT 1 FROM dbo.Fn_split(@vchtypes,',') c WHERE a.Vchtype = c.a)
	AND EXISTS(SELECT 1 FROM #ptypetmp pp WHERE pp.ptypeid = a.PtypeId)
	AND EXISTS(SELECT 1 FROM #ktypetmp kk WHERE kk.KtypeId = a.KtypeId)
	AND (EXISTS(SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = a.PtypeId AND pa.AttributeID = @assisttypevalue) OR @assisttypevalue=-1)
	GROUP BY a.PtypeId, b.SizeID,b.ColorID
	
	IF object_id('tempdb..#stockData') is not null   
    drop table #stockData
	SELECT a.PtypeId,b.ColorId,b.SizeId,SUM(b.Qty) AS stockqty
	INTO #stockData
	FROM dbo.GoodsStocks a INNER JOIN dbo.Goodsstockdetail b ON a.OrderId = b.OrderId
	WHERE EXISTS(SELECT 1 FROM #ktypetmp kk WHERE kk.KtypeId = a.KtypeId)
	AND (EXISTS(SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = a.PtypeId AND pa.AttributeID = @assisttypevalue) OR @assisttypevalue=-1)
	AND b.ColorID = CASE WHEN @pcrec<>-1 THEN @pcrec ELSE b.ColorID END
	AND b.SizeID = CASE WHEN @psrec<>-1 THEN @psrec ELSE b.SizeID END
	GROUP BY a.PtypeId,b.ColorId,b.SizeId
	
	SELECT dd.PtypeId,RIGHT('00000'+ CAST(dd.SizeID AS VARCHAR),5) AS pstypeid,RIGHT('00000'+ CAST(dd.ColorID AS VARCHAR),5) AS pctypeid,dd.qty,ISNULL(sd.stockqty,0) AS stockqty,0 AS isselected
	FROM #data dd LEFT JOIN #stockData sd ON dd.PtypeId = sd.PtypeId AND dd.ColorID = sd.ColorId AND dd.SizeID = sd.SizeId
	UNION ALL
	SELECT pp.ptypeid,RIGHT('00000'+ CAST(ps.SizeID AS VARCHAR),5) AS pstypeid,RIGHT('00000'+ CAST(pc.ColorID AS VARCHAR),5) AS pctypeid,0 AS qty,ISNULL(sd.stockqty,0) AS stockqty,0 AS isselected
	FROM #ptypetmp pp INNER JOIN dbo.PtypeColor pc ON pp.ptypeid = pc.PtypeId
	INNER JOIN dbo.PtypeSize ps ON pc.PtypeId = ps.PtypeId
	LEFT JOIN #stockData sd ON ps.PtypeId = sd.PtypeId AND ps.SizeID = sd.SizeId AND pc.ColorId = sd.ColorId
	WHERE pp.IssueDate BETWEEN @publish_s AND @publish_e
	AND NOT EXISTS(SELECT 1 FROM #data ss WHERE ss.PtypeId = pp.ptypeid)
	
END 
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/******************************************20130903********************************************/
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO
 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BranchPHApply]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROC BranchPHApply
 GO
CREATE PROCEDURE BranchPHApply  
    ( 
		@date_s                VARCHAR(20),
		@date_e                VARCHAR(20),
		@bctypeid              VARCHAR(50),
		@ktypeid               VARCHAR(50),
		@ptypeid               VARCHAR(50),
		@pcrec                 INT,
		@psrec                 INT,
		@assisttypevalue       INT,
		@saletype              VARCHAR(20),
		@publish_s             VARCHAR(20),
		@publish_e             VARCHAR(20),
		@operatorID            VARCHAR(50)
    )  
AS  
BEGIN
    DECLARE @vchtypes VARCHAR(1000)
    SET @vchtypes = ''
    IF @saletype = '0'
    BEGIN
    SET @vchtypes = '11,24,45';
    END
    ELSE
    IF @saletype = '1'
    BEGIN
    SET @vchtypes = '12,100'; 
    END
    ELSE
    BEGIN
    SET @vchtypes = '11,24,45,12,100'; 
    END
    
    IF object_id('tempdb..#ptypetmp') is not null   
    drop table #ptypetmp
    SELECT TypeID AS ptypeid,IssueDate
    INTO #ptypetmp
    FROM dbo.FN_GetPowerRangePList(@operatorID,@ptypeid)
    
    IF object_id('tempdb..#ktypetmp') is not null   
    drop table #ktypetmp
    SELECT KtypeId
    INTO #ktypetmp
    FROM dbo.FN_GetStockListOfBranch(@operatorID,@bctypeid,@ktypeid)
    
    IF object_id('tempdb..#data') is not null   
    drop table #data
	SELECT a.PtypeId,b.SizeID,b.ColorID,SUM(-b.Qty) AS qty
	INTO #data
	FROM dbo.DlyData a INNER JOIN dbo.DlyDataDetail b ON a.Vchcode = b.Vchcode AND a.DlyOrder = b.DlyOrder
	WHERE a.[Date] BETWEEN @date_s AND @date_e
	AND a.RedOld = 'F'
	AND b.ColorID = CASE WHEN @pcrec<>-1 THEN @pcrec ELSE b.ColorID END
	AND b.SizeID = CASE WHEN @psrec<>-1 THEN @psrec ELSE b.SizeID END
	AND EXISTS(SELECT 1 FROM dbo.Fn_split(@vchtypes,',') c WHERE a.Vchtype = c.a)
	AND EXISTS(SELECT 1 FROM #ptypetmp pp WHERE pp.ptypeid = a.PtypeId)
	AND EXISTS(SELECT 1 FROM #ktypetmp kk WHERE kk.KtypeId = a.KtypeId)
	AND (EXISTS(SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = a.PtypeId AND pa.AttributeID = @assisttypevalue) OR @assisttypevalue=-1)
	GROUP BY a.PtypeId, b.SizeID,b.ColorID
	ORDER BY a.PtypeId,b.ColorID
	
	IF object_id('tempdb..#stockData') is not null   
    drop table #stockData
	SELECT a.PtypeId,b.ColorId,b.SizeId,SUM(b.Qty) AS stockqty
	INTO #stockData
	FROM dbo.GoodsStocks a INNER JOIN dbo.Goodsstockdetail b ON a.OrderId = b.OrderId
	WHERE EXISTS(SELECT 1 FROM #ktypetmp kk WHERE kk.KtypeId = a.KtypeId)
	AND (EXISTS(SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = a.PtypeId AND pa.AttributeID = @assisttypevalue) OR @assisttypevalue=-1)
	AND b.ColorID = CASE WHEN @pcrec<>-1 THEN @pcrec ELSE b.ColorID END
	AND b.SizeID = CASE WHEN @psrec<>-1 THEN @psrec ELSE b.SizeID END
    GROUP BY a.PtypeId,b.ColorId,b.SizeId
	
	IF object_id('tempdb..#Noqtydata') is not null   
    drop table #Noqtydata
	SELECT pp.ptypeid,RIGHT('00000'+ CAST(ps.SizeID AS VARCHAR),5) AS pstypeid,RIGHT('00000'+ CAST(pc.ColorID AS VARCHAR),5) AS pctypeid,0 AS qty,ISNULL(sd.stockqty,0) AS stockqty,0 AS isselected
	INTO #Noqtydata
	FROM #ptypetmp pp INNER JOIN dbo.PtypeColor pc ON pp.ptypeid = pc.PtypeId
	INNER JOIN dbo.PtypeSize ps ON pc.PtypeId = ps.PtypeId
	LEFT JOIN #stockData sd ON ps.PtypeId = sd.PtypeId AND ps.SizeID = sd.SizeId AND pc.ColorId = sd.ColorId
	WHERE pp.IssueDate BETWEEN @publish_s AND @publish_e
	AND NOT EXISTS(SELECT 1 FROM #data ss WHERE ss.PtypeId = pp.ptypeid)
	ORDER BY pp.ptypeid,RIGHT('00000'+ CAST(pc.ColorID AS VARCHAR),5)
	
	SELECT dd.PtypeId,RIGHT('00000'+ CAST(dd.SizeID AS VARCHAR),5) AS pstypeid,RIGHT('00000'+ CAST(dd.ColorID AS VARCHAR),5) AS pctypeid,dd.qty,ISNULL(sd.stockqty,0) AS stockqty,0 AS isselected
	FROM #data dd LEFT JOIN #stockData sd ON dd.PtypeId = sd.PtypeId AND dd.ColorID = sd.ColorId AND dd.SizeID = sd.SizeId
	UNION ALL
	SELECT ptypeid,pstypeid,pctypeid,qty,stockqty,isselected
	FROM #Noqtydata
END 
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].[FZSaveToGatheringDly]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FZSaveToGatheringDly]
GO




--  *************************************************************************************************************************************
--  ||                                                                                        
--  ||   过程名称： FZSaveToGatheringDly                                    
--  ||   过程功能：保存按单结算明细  修改：老罗 2011-03-05
--  ||=========================================================================================
--  ||   参数说明：  参数名称         类型            意义                     输入输出
--  ||            -----------------------------------------------------------------------------
--  ||                @szBTypeID    varchar(50),         往来单位
--  ||                @nVchCode     int,                       传入nVchcode=0,则删除收款单对应的所有明细
--  ||					        对于物流单据，传入total=0,则将物流对应的收款明细删除
--  ||                @nGatheringVchCode int,            保存的结算单的单据号
--  ||                @dTotal           numeric(24,10),
--  ||                @nType           int                         付款为2    收款为1 (-1不做处理)
--  ||=========================================================================================   
--  ||   返回值：         值                                     说明
--  ||       ----------------------------------------------------------------------------------------
--  ||                    0                                 执行成功
--  ||                  －1                               执行失败
--  ||==========================================================================================
CREATE PROCEDURE FZSaveToGatheringDly
(
	@szBTypeID varchar(50),
	@nVchCode int,
	@nGatheringVchCode int,
	@dTotal numeric(24,10),
	@nType int,
	@Banlance numeric(24,10),
	@Draft  int = 0,
	@IsRPBill int = 0,
	@MarketDiscount numeric(24,10) = 0,
	@VchTotal   numeric(24,10) = 0
)
AS
	SET NOCOUNT ON
	declare @tmptotal numeric(24,10)
	set @Draft = isnull(@Draft,0)
	set @MarketDiscount = isnull(@MarketDiscount,0)
	set @VchTotal = isnull(@VchTotal,0)
	If @nType = -1
	Begin
	   return 0
	End
	--Begin Modify by 2011-3-4 明天又是学雷锋了，今天做个好事把这个并发问题处理了。
	--对于已过账的收付款单重新结算，取得最新的结算余额（有并发操作时会出现传入的结算余额与当前单据实际应结算余额不同）
	If @IsRPBill = 1
	Begin
		Declare @BranchId varchar(50)
		Declare @dCurBanlance numeric(24,10)
		Declare @nGatheringVchType INT
		DECLARE	 @PHID INT
		Select @BranchId=BranchId, @nGatheringVchType=VchType,@PHID=PHID From DlyNdx Where VchCode = @nGatheringVchCode
		If @nVchCode = -1
		Begin
			--获得当前期初结算余额
			If (@nGatheringVchType = 4) OR (@nGatheringVchType = 253 AND (@nType = 3 OR @nType = 5))		--收款单
				Select @dCurBanlance = (isnull(bb.ARTotal00,0) - isnull((
						Select sum(isnull(Total,0)) From GatheringDly 
						Where Btypeid = @szBTypeID and vchCode = -1 and Type IN (1,3,5) and draft<>1 
							And GatheringVchCode In (Select VchCode From DlyNdx where VchType IN (4,253) and branchid=@BranchId and redold = 'F')
						),0)) 
				From btype b,BranchBtype bb 
				Where b.typeid = @szBTypeID And b.typeid=bb.btypeid and bb.branchid=@BranchId 
	
			If (@nGatheringVchType = 66) OR (@nGatheringVchType = 253 AND (@nType =4 OR @nType = 6)) 		--付款单
				Select @dCurBanlance = (isnull(bb.APTotal00,0) - isnull((
						Select sum(isnull(Total,0)) From GatheringDly 
						Where Btypeid = @szBTypeID and vchCode = -1 and Type IN (2,4,6) and draft<>1 
							And GatheringVchCode In (Select VchCode From DlyNdx where VchType IN (66,253)  and branchid=@BranchId and redold = 'F')
						),0)) 
				From btype b,BranchBtype bb 
				Where b.typeid = @szBTypeID And b.typeid=bb.btypeid and bb.branchid=@BranchId 
			
			Select @dCurBanlance=abs(@dCurBanlance)
		End
		Else
		Begin
			If Exists(Select 1 From DlyNdx Where VchCode=@nVchCode And Draft=2 And redold = 'F')
			Begin
				--获得当前物流单据结算余额
				Select @dCurBanlance = abs(BalanceTotal) From FN_view_zz_VchBalance_New b Where b.VchCode = @nVchCode
			End
		End
	
		Set @dCurBanlance = IsNull(@dCurBanlance,0)
		--判断当前结算余额是否小于结算金额
		If @dCurBanlance < abs(@dTotal)
		Begin
			If @dCurBanlance = @Banlance
				return -200
			Else
				return -201
		End
	End
	--End 2011-3-4

	if Exists(Select * from GatheringDly where BTypeID=@szBTypeID and VchCode=@nVchCode and GatheringVchCode=@nGatheringVchCode and [Type]=@nType)
        	Update GatheringDly Set Total=@dTotal,
		                              Draft = @Draft ,
		                              MarketDiscount = @MarketDiscount,
		                              VchTotal = @VchTotal
        	where BTypeID=@szBTypeID and VchCode=@nVchCode and GatheringVchCode=@nGatheringVchCode  and [Type]=@nType
	else	
		Insert Into GatheringDly (BTypeID, VchCode, GatheringVchCode, Total, [Type],Banlance,Draft,MarketDiscount,VchTotal) 
		Values(@szBTypeID, @nVchCode, @nGatheringVchCode, @dTotal,@nType,@Banlance,@Draft,@MarketDiscount,@VchTotal)
if @@Error=0
	RETURN 0
else	RETURN -100




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/******************************************20130922********************************************/
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO
 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BranchPHApply]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
 DROP PROC BranchPHApply
 GO
CREATE PROCEDURE BranchPHApply  
    ( 
		@date_s                VARCHAR(20),
		@date_e                VARCHAR(20),
		@bctypeid              VARCHAR(50),
		@ktypeid               VARCHAR(50),
		@ptypeid               VARCHAR(50),
		@pcrec                 INT,
		@psrec                 INT,
		@assisttypevalue       INT,
		@saletype              VARCHAR(20),
		@publish_s             VARCHAR(20),
		@publish_e             VARCHAR(20),
		@operatorID            VARCHAR(50)
    )  
AS  
BEGIN
    DECLARE @vchtypes VARCHAR(1000)
    SET @vchtypes = ''
    IF @saletype = '0'
    BEGIN
    SET @vchtypes = '11,24,45';
    END
    ELSE
    IF @saletype = '1'
    BEGIN
    SET @vchtypes = '12,100'; 
    END
    ELSE
    BEGIN
    SET @vchtypes = '11,24,45,12,100'; 
    END
    
    IF object_id('tempdb..#ptypetmp') is not null   
    drop table #ptypetmp
    SELECT TypeID AS ptypeid,IssueDate,RetailPrice
    INTO #ptypetmp
    FROM dbo.FN_GetPowerRangePList(@operatorID,@ptypeid)
    
    IF object_id('tempdb..#ktypetmp') is not null   
    drop table #ktypetmp
    SELECT KtypeId
    INTO #ktypetmp
    FROM dbo.FN_GetStockListOfBranch(@operatorID,@bctypeid,@ktypeid)
    
    IF object_id('tempdb..#data') is not null   
    drop table #data
	SELECT a.PtypeId,b.SizeID,b.ColorID,SUM(-b.Qty) AS qty,pp.RetailPrice,-SUM(Convert(NUMERIC(24,10),b.Qty)*Convert(NUMERIC(24,10),pp.RetailPrice)) AS retailtotal
	INTO #data
	FROM dbo.DlyData a INNER JOIN dbo.DlyDataDetail b ON a.Vchcode = b.Vchcode AND a.DlyOrder = b.DlyOrder
	INNER JOIN #ptypetmp pp ON a.PtypeId = pp.ptypeid
	WHERE a.[Date] BETWEEN @date_s AND @date_e
	AND a.RedOld = 'F'
	AND b.ColorID = CASE WHEN @pcrec<>-1 THEN @pcrec ELSE b.ColorID END
	AND b.SizeID = CASE WHEN @psrec<>-1 THEN @psrec ELSE b.SizeID END
	AND EXISTS(SELECT 1 FROM dbo.Fn_split(@vchtypes,',') c WHERE a.Vchtype = c.a)
	--AND EXISTS(SELECT 1 FROM #ptypetmp pp WHERE pp.ptypeid = a.PtypeId)
	AND EXISTS(SELECT 1 FROM #ktypetmp kk WHERE kk.KtypeId = a.KtypeId)
	AND (EXISTS(SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = a.PtypeId AND pa.AttributeID = @assisttypevalue) OR @assisttypevalue=-1)
	GROUP BY a.PtypeId, b.SizeID,b.ColorID,pp.RetailPrice
	ORDER BY a.PtypeId,b.ColorID
	
	IF object_id('tempdb..#stockData') is not null   
    drop table #stockData
	SELECT a.PtypeId,b.ColorId,b.SizeId,SUM(b.Qty) AS stockqty
	INTO #stockData
	FROM dbo.GoodsStocks a INNER JOIN dbo.Goodsstockdetail b ON a.OrderId = b.OrderId
	WHERE EXISTS(SELECT 1 FROM #ktypetmp kk WHERE kk.KtypeId = a.KtypeId)
	AND (EXISTS(SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = a.PtypeId AND pa.AttributeID = @assisttypevalue) OR @assisttypevalue=-1)
	AND b.ColorID = CASE WHEN @pcrec<>-1 THEN @pcrec ELSE b.ColorID END
	AND b.SizeID = CASE WHEN @psrec<>-1 THEN @psrec ELSE b.SizeID END
    GROUP BY a.PtypeId,b.ColorId,b.SizeId
	
	IF object_id('tempdb..#Noqtydata') is not null   
    drop table #Noqtydata
	SELECT pp.ptypeid,RIGHT('00000'+ CAST(ps.SizeID AS VARCHAR),5) AS pstypeid,RIGHT('00000'+ CAST(pc.ColorID AS VARCHAR),5) AS pctypeid,0 AS qty,ISNULL(sd.stockqty,0) AS stockqty,0 AS isselected,pp.RetailPrice,0 AS retailtotal
	INTO #Noqtydata
	FROM #ptypetmp pp INNER JOIN dbo.PtypeColor pc ON pp.ptypeid = pc.PtypeId
	INNER JOIN dbo.PtypeSize ps ON pc.PtypeId = ps.PtypeId
	LEFT JOIN #stockData sd ON ps.PtypeId = sd.PtypeId AND ps.SizeID = sd.SizeId AND pc.ColorId = sd.ColorId
	WHERE pp.IssueDate BETWEEN @publish_s AND @publish_e
	AND NOT EXISTS(SELECT 1 FROM #data ss WHERE ss.PtypeId = pp.ptypeid)
	ORDER BY pp.ptypeid,RIGHT('00000'+ CAST(pc.ColorID AS VARCHAR),5)
	
	SELECT dd.PtypeId,RIGHT('00000'+ CAST(dd.SizeID AS VARCHAR),5) AS pstypeid,RIGHT('00000'+ CAST(dd.ColorID AS VARCHAR),5) AS pctypeid,dd.qty,ISNULL(sd.stockqty,0) AS stockqty,0 AS isselected,RetailPrice,retailtotal
	FROM #data dd LEFT JOIN #stockData sd 
	ON dd.PtypeId = sd.PtypeId AND dd.ColorID = sd.ColorId AND dd.SizeID = sd.SizeId
	UNION ALL
	SELECT ptypeid,pstypeid,pctypeid,qty,stockqty,isselected,RetailPrice,retailtotal
	FROM #Noqtydata
END 
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
/******************************************20131021********************************************/
IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZBtypeSaleAnalyse_BS]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZBtypeSaleAnalyse_BS]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
  作者:QF
  时间:2011-09-19			
  主要内容:BS端，退货方式分为[正常退货,次品退货,其他退货等等]，由于合并相对麻烦，分开为宜

*/

CREATE PROCEDURE FZBtypeSaleAnalyse_BS
    (
      @szPtypeId VARCHAR(50) ,
      @szKtypeid VARCHAR(50) ,
      @szBtypeid VARCHAR(50) ,
      @szBeginData VARCHAR(50) ,
      @szEndData VARCHAR(50) ,
      @ifstop VARCHAR(2) ,
      @Etypeid VARCHAR(50) ,
      @Dtypeid VARCHAR(50) ,
      @A1 VARCHAR(8000) = '' ,--品牌  
      @A2 VARCHAR(8000) = '' ,--季节  
      @A3 VARCHAR(8000) = '' ,--辅助属性1  
      @A4 VARCHAR(8000) = '' ,--辅助属性2     
      @branchid VARCHAR(8000) ,
      @OperatorId VARCHAR(50) ,
      @OpID INT = 0   --0-全部 , 其他为具体类型  
    )
AS 


    DECLARE @OperatorIsJM BIT    
    SELECT  @OperatorIsJM = SelfHelp
    FROM    Branch a
            LEFT JOIN Employee b ON a.branchid = b.branchid
    WHERE   b.typeid = @OperatorId    
    
    DECLARE @szparid VARCHAR(50)      
    
    IF @szBtypeId IS NULL
        OR @szBtypeId = '' 
        SET @szparid = '00000'      
    ELSE 
        SET @szparid = @szBtypeId      
    
    IF @szBtypeId IS NULL 
        SET @szBtypeId = ''      
    
    IF @branchid IS NULL 
        SET @branchid = ''      
    
    DECLARE @str VARCHAR(10)         
    IF LEFT(@branchid, 5) = '00001'
        OR @branchid = '' 
        BEGIN        
            SET @str = '2,3,4'              
        END        
    ELSE 
        BEGIN        
            SET @str = '6'           
        END      
  
    IF OBJECT_ID('tempdb..#TmpP') IS NOT NULL 
        DROP TABLE #TmpP
    CREATE TABLE #TmpP ( PTypeID VARCHAR(50) )
    DECLARE @singlePtypeid INT
-- @A2 季节
    IF @A2 = '' 
        BEGIN
            INSERT  INTO #TmpP ( PTypeID )
                    SELECT  TypeId
                    FROM    dbo.FN_GetPowerRangePList(@Operatorid, '%')
        END
    ELSE 
        BEGIN
            WHILE CHARINDEX(',', @A2) > 0 
                BEGIN
                    SELECT  @singlePtypeid = CAST(LEFT(@A2, CHARINDEX(',', @A2) - 1) AS INT)
		
                    INSERT  INTO #TmpP ( PTypeID )
                            SELECT  a.PtypeId
                            FROM    dbo.PtypeAttribute a
                            WHERE   a.AttributeID = @singlePtypeid
                                    AND PtypeId NOT IN ( SELECT PTypeID FROM #TmpP )
                    SELECT  @A2 = SUBSTRING(@A2, CHARINDEX(',', @A2) + 1, LEN(@A2))
                END
        END  

-----------
		IF object_id('tempdb..#P') is not null  
			drop table #P
		IF object_id('tempdb..#b') is not null  
			drop table #b
		IF object_id('tempdb..#e') is not null  
			drop table #e
		IF object_id('tempdb..#br') is not null  
			drop table #br
		SELECT TypeId INTO #P FROM  FN_GetPowerRangePList(@OperatorId, @szPtypeId)
		SELECT Typeid INTO #b FROM  FN_GetPowerRangeBList(@OperatorId, @szBtypeid, '2,3,4,6')
		SELECT Typeid INTO #e FROM  FN_GetPowerRangeEList(@OperatorId, @EtypeID)
		SELECT KtypeId,selfhelp INTO #br FROM  FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid)

		CREATE CLUSTERED INDEX I_tmp_typeid ON #TmpP(PTypeID)
		CREATE CLUSTERED INDEX I_p_typeid ON #P(TypeId)
		CREATE CLUSTERED INDEX I_e_typeid ON #e(TypeId)
		CREATE CLUSTERED INDEX I_b_typeid ON #b(TypeId)
		CREATE CLUSTERED INDEX I_br_typeid ON #br(KtypeId)
		
	  SELECT    s.Btypeid ,           --销售数量(不包括补货)      
                ds.[qty]			AS [Qty] ,
                ds.[bargaintotal]   AS STotal ,
                ds.[qty]			AS [TQty] ,
                ds.[bargaintotal]	AS TTotal , 
                ds.[qty]			AS SupplyQty ,
                ds.[bargaintotal]	AS SupplyTotal ,
                ds.CostTotal		AS CostTotal ,
                ds.[bargaintotal]	AS SaleMoney ,
                ds.[taxtotal]		AS Taxtotal ,
                ds.[tax_total]		AS Tax_total ,
                ds.[total]			AS total ,
                ds.bargaintotal		AS BargainTotal,
                ifSupply,
                vchtype
      INTO		#temp_data
      FROM      DlyData S 
                INNER JOIN dlydatadetail ds ON s.dlyorder = ds.dlyorder
      WHERE     S.[date] between @szBeginData and @szEndData 
                AND s.BillType = 2 
                AND s.redold = 'F'  
                AND s.OpId=CASE WHEN @OpID = 0 THEN s.Opid ELSE @OpID END
                AND s.usedtype = CASE WHEN s.vchtype IN ( 222, 224 ) THEN 1 ELSE s.usedtype END
                AND EXISTS ( SELECT 1 FROM #TmpP a WHERE s.ptypeid = a.ptypeid )
                AND EXISTS ( SELECT 1 FROM   FN_GetPowerRangeVList(@BranchId) FilterV WHERE  s.vchtype = FilterV.vchtype ) 
                AND s.Dtypeid LIKE @Dtypeid + '%'  --以后换成权限方式     
                AND (EXISTS ( SELECT 1 FROM   #P FilterP WHERE  s.PtypeId = FilterP.TypeId ))
                AND (EXISTS ( SELECT 1 FROM   #b FilterB WHERE  s.BtypeId = FilterB.TypeId ))
                AND (EXISTS ( SELECT 1 FROM   #e FilterE WHERE  s.EtypeId = FilterE.TypeId ))
                AND EXISTS ( SELECT 1 FROM  #br FilterK WHERE  s.ktypeId = Filterk.KtypeId AND selfhelp = @OperatorIsJM )
                AND s.BranchId LIKE @BranchId + '%'
                

-----------
    SELECT  p.[typeid] AS Btypeid ,
            SUM(qty) AS qty ,
            SUM(Tqty) Tqty ,
            SUM(TTotal) AS TTotal ,
            SUM(qty) - SUM(Tqty) - SUM(Bqty) + SUM(ISNULL(SupplyQty, 0)) AS Sqty ,
            SUM(Tax_total) AS tax_total ,
            SUM(taxtotal) AS taxtotal ,
            SUM(SaleMoney) AS STotal ,
            SUM(STotal) AS Total ,
            SUM(Total) - SUM(BargainTotal) AS ConvertTotal ,
            SUM(SaleMoney) - SUM(Tax_total) AS DeductTotal ,
            SUM(CostTotal) AS CostTotal ,
            SUM(SaleMoney) - SUM(CostTotal) AS Profittotal ,
            SUM(ISNULL(BQty, 0)) AS BQty ,
            SUM(ISNULL(BTotal, 0)) AS BTotal ,
            SUM(ISNULL(BQty, 0)) + SUM(Tqty) AS BSumQty ,
            SUM(ISNULL(BTotal, 0)) + SUM(TTotal) AS BSumTotal ,
            SUM(ISNULL(SupplyQty, 0)) AS SupplyQty ,
            SUM(ISNULL(SupplyTotal, 0)) AS SupplyTotal ,
            CAST(CAST(( CASE WHEN SUM(Total) = 0 THEN 0 ELSE ( SUM(Total) - SUM(BargainTotal) ) / SUM(Total) END * 100 ) AS NUMERIC(24, 2)) AS VARCHAR(30)) + '%' AS RLrate ,
            usertype
    FROM    ( SELECT    p.[typeid] ,
                        ISNULL([Qty], 0) AS [Qty] ,
                        ISNULL([SaleMoney], 0) AS [SaleMoney] ,
                        ISNULL(Total, 0) AS Total ,
                        ISNULL([taxtotal], 0) AS Taxtotal ,
                        ISNULL([tax_total], 0) AS Tax_total ,
                        ISNULL(BargainTotal, 0) AS BargainTotal ,
                        ISNULL(Tqty, 0) AS Tqty ,
                        ISNULL(TTotal, 0) AS TTotal ,
                        ISNULL(STotal, 0) AS STotal ,
                        ISNULL(CostTotal, 0) AS CostTotal ,
                        ISNULL(BQty, 0) AS BQty ,
                        ISNULL(BTotal, 0) AS BTotal ,
                        ISNULL(SupplyQty, 0) AS SupplyQty ,
                        ISNULL(SupplyTotal, 0) AS SupplyTotal ,
                        usertype
              FROM      ( SELECT    TypeId , usertype
                          FROM      FN_GetPowerRangeBTree(@OperatorId, @szBtypeid, @str)
                          WHERE     ( @branchid = CASE @str WHEN '6' THEN LEFT(branchid, LEN(@branchid)) ELSE @branchid END )
                                    OR ( branchid = CASE @str WHEN '6' THEN LEFT(@branchid, LEN(branchid)) ELSE branchid END )
                        ) p
                        LEFT JOIN ( SELECT  SUBSTRING(Btypeid, 1, LEN(@szBtypeid) + 5) AS Btypeid ,
                                            SUM(ISNULL(-qty, 0)) qty ,
                                            SUM(ISNULL(-STotal, 0)) STotal ,
                                            SUM(ISNULL(tqty, 0)) tqty ,
                                            SUM(ISNULL(TTotal, 0)) TTotal ,
                                            SUM(ISNULL(-salemoney, 0)) salemoney ,
                                            SUM(ISNULL(-taxtotal, 0)) taxtotal ,
                                            SUM(ISNULL(-Tax_total, 0)) Tax_total ,
                                            SUM(ISNULL(-Total, 0)) Total ,
                                            SUM(ISNULL(-BargainTotal, 0)) BargainTotal ,
                                            SUM(ISNULL(-CostTotal, 0)) AS CostTotal ,
                                            SUM(ISNULL(BQty, 0)) AS BQty ,
                                            SUM(ISNULL(BTotal, 0)) AS BTotal ,
                                            SUM(ISNULL(-SupplyQty, 0)) AS SupplyQty ,
                                            SUM(ISNULL(-SupplyTotal, 0)) AS SupplyTotal
                                    FROM    ( SELECT    Btypeid ,           --销售数量(不包括补货)      
                                                        SUM(ISNULL([qty], 0)) AS [Qty] ,
                                                        SUM(ISNULL(STotal, 0)) AS STotal ,
                                                        0 AS [TQty] ,
                                                        0 AS TTotal ,
                                                        0 AS BQty ,
                                                        0 AS BTotal ,
                                                        0 AS SupplyQty ,
                                                        0 AS SupplyTotal ,
                                                        SUM(ISNULL(CostTotal, 0)) AS CostTotal ,
                                                        SUM(ISNULL(SaleMoney, 0)) AS SaleMoney ,
                                                        SUM(ISNULL(Taxtotal, 0)) AS Taxtotal ,
                                                        SUM(ISNULL(Tax_total, 0)) AS Tax_total ,
                                                        SUM(ISNULL([total], 0)) AS total ,
                                                        SUM(ISNULL(bargaintotal, 0)) AS BargainTotal
                                              FROM      #temp_data
                                              WHERE     ifSupply = 0 AND qty < 0
                                              GROUP BY  Btypeid , vchtype
                                              UNION ALL
                                              SELECT    Btypeid , --     补货数量      
                                                        0 AS [Qty] ,
                                                        0 AS STotal ,
                                                        0 AS [TQty] ,
                                                        0 AS TTotal ,
                                                        0 AS BQty ,
                                                        0 AS BTotal ,
                                                        SUM(ISNULL(SupplyQty, 0)) AS SupplyQty ,
                                                        SUM(ISNULL(SupplyTotal, 0)) AS SupplyTotal ,
                                                        SUM(ISNULL(CostTotal, 0)) AS CostTotal ,
                                                        SUM(ISNULL(SaleMoney, 0)) AS SaleMoney ,
                                                        SUM(ISNULL(Taxtotal, 0)) AS Taxtotal ,
                                                        SUM(ISNULL(Tax_total, 0)) AS Tax_total ,
                                                        SUM(ISNULL(total, 0)) AS total ,
                                                        SUM(ISNULL(BargainTotal, 0)) AS BargainTotal
                                              FROM      #temp_data
                                              WHERE     ifSupply = 1 AND qty < 0
                                              GROUP BY  Btypeid , vchtype
                                              UNION ALL
                                              SELECT    Btypeid ,  -- 退货数量      
                                                        0 AS [Qty] ,
                                                        0 AS STOtal ,
                                                        SUM(ISNULL([TQty], 0)) AS [TQty] ,
                                                        SUM(ISNULL(TTotal, 0)) AS TTotal ,
                                                        0 AS BQty ,
                                                        0 AS BTotal ,
                                                        0 AS SupplyQty ,
                                                        0 AS SupplyTotal ,
                                                        SUM(ISNULL(CostTotal, 0)) AS CostTotal ,
                                                        SUM(ISNULL(SaleMoney, 0)) AS SaleMoney ,
                                                        SUM(ISNULL(Taxtotal, 0)) AS Taxtotal ,
                                                        SUM(ISNULL(Tax_total, 0)) AS Tax_total ,
                                                        SUM(ISNULL(total, 0)) AS total ,
                                                        SUM(ISNULL(BargainTotal, 0)) AS BargainTotal
                                              FROM      #temp_data
                                              WHERE     qty > 0
                                              GROUP BY  Btypeid , vchtype          
                                            ) C
                                    GROUP BY SUBSTRING(Btypeid, 1,
                                                       LEN(@szBtypeid) + 5)
                                  ) Salebill ON p.[typeid] = Salebill.Btypeid
	            ) p
	    GROUP BY p.[typeid] ,
	            usertype
    ORDER BY p.[typeid] ,
            usertype             
    DROP TABLE #TmpP       
     
    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].[FZSaleAnalyse_BS]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZSaleAnalyse_BS]
GO

/*
  作者:QF
  时间:2011-09-19			
  主要内容:BS端，退货方式分为[正常退货,次品退货,其他退货等等]，由于合并相对麻烦，分开为宜

*/

 CREATE PROCEDURE FZSaleAnalyse_BS
    (
      @szPtypeId VARCHAR(50),
      @szKtypeid VARCHAR(2000),
      @szBtypeid VARCHAR(50),
      @szBeginData VARCHAR(50),
      @szEndData VARCHAR(50),
      @ifstop VARCHAR(2),
      @Etypeid VARCHAR(50),
      @SaleTraitName VARCHAR(1000),
      @Dtypeid VARCHAR(50),
      @CustType VARCHAR(10),
      @branchid VARCHAR(2000),
      @vchtype VARCHAR(100),
      @OperatorId VARCHAR(50),
	@OpID		INT = 0   --0-全部 , 其他为具体类型 
    )
 AS 
 
--select * into #FilterK from FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid)

    DECLARE @szparid VARCHAR(50)

    IF @SaleTraitName = '全部' 
        SET @SaleTraitName = '' 

    IF @szPtypeId IS NULL
        OR @szPtypeId = '' 
        SELECT  @szparid = '00000'
    ELSE 
        SELECT  @szparid = @szPtypeId

    IF @szPtypeId IS NULL 
        SELECT  @szPtypeId = ''

    IF @branchid = ',' 
        SET @branchid = ''
--总部和加盟商共用一个，当不进行筛选单据的情况下，要把单据范围补齐
    IF LEFT(@branchid, 5) = '00001'
        OR @branchid = '' 
        BEGIN
            IF @vchtype IS NULL
                OR @vchtype = '' 
                SET @vchtype = '100,11,45,24,12,222,224'	--总部统计的销售主体单据
        END
    ELSE 
        BEGIN
            IF @vchtype IS NULL
                OR @vchtype = '' 
                SET @vchtype = '11,12,45,24'			--加盟商统计的销售主体单据
        END
    IF OBJECT_ID('tempdb..#temp_p') IS NOT NULL 
        DROP TABLE #temp_p
    IF OBJECT_ID('tempdb..#temp') IS NOT NULL 
        DROP TABLE #temp
    IF OBJECT_ID('tempdb..#FilterKInfo') IS NOT NULL 
        DROP TABLE #FilterKInfo
    IF OBJECT_ID('tempdb..#FilterVList') IS NOT NULL 
        DROP TABLE #FilterVList
    IF OBJECT_ID('tempdb..#FilterVList') IS NOT NULL 
        DROP TABLE #FilterVList
    IF OBJECT_ID('tempdb..#TempPtree') IS NOT NULL 
        DROP TABLE #TempPtree        
    IF OBJECT_ID('tempdb..#TempBList') IS NOT NULL 
        DROP TABLE #TempBList        
    IF OBJECT_ID('tempdb..#TempEList') IS NOT NULL 
        DROP TABLE #TempEList                
    IF OBJECT_ID('tempdb..#temp_data') IS NOT NULL 
        DROP TABLE #temp_data        
        
	select [typeid],porder into #TempPtree FROM FN_GetPowerRangePTree(@OperatorId, @szPtypeId) WHERE    deleted = 0 AND [typeid] <> '00000' AND (@ifstop <> '0' or stop = '0')
		        
	select Typeid Into #TempBList from FN_GetPowerRangeBList(@OperatorId, @szBtypeid, '2,3,4,6')

	select Typeid Into #TempEList from FN_GetPowerRangeEList(@OperatorId, @EtypeID) 

    SELECT  typeid
    INTO    #temp_p
    FROM    FN_GetPowerRangePList(@OperatorId, @szPtypeId) --ptype 
    WHERE   stop = CASE @ifstop WHEN '0' THEN '0' ELSE stop END

	select KtypeId into #FilterKInfo from FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid)		

	SELECT GetID into #FilterVInfo FROM   FN_GetIdStrListTable(@vchtype)

	declare @tembranchid varchar(50)
	SET @tembranchid =LEFT(@branchid,50)
	SELECT vchtype into #FilterVList FROM   FN_GetPowerRangeVList(@tembranchid) 
	
	CREATE CLUSTERED INDEX I_tmp_typeid ON #temp_p(typeid)
	CREATE CLUSTERED INDEX I_b_typeid ON #TempBList(typeid)
	CREATE CLUSTERED INDEX I_e_typeid ON #TempEList(typeid)
	CREATE CLUSTERED INDEX I_k_typeid ON #FilterKInfo(KtypeId)
	CREATE CLUSTERED INDEX I_v_typeid ON #FilterVList(vchtype)
	CREATE CLUSTERED INDEX I_v_getid ON #FilterVInfo(getid)
	
--解决BUG-515 错误原因:同一张销售换货单中,即出库又入库的商品被聚合了
SELECT    Ptypeid,  
        --SUM(dd.[qty]) AS [Qty],
        --SUM(dd.[BargainTotal]) AS STotal,
        --SUM(dd.[qty]) AS [TQty],
        --SUM(dd.[BargainTotal]) AS TTotal,
        (dd.[qty]) AS [Qty],
        (dd.[BargainTotal]) AS STotal,
        (dd.[qty]) AS [TQty],
        (dd.[BargainTotal]) AS TTotal,
        0 AS BQty,
        0 AS BTotal,
		--SUM(dd.[qty]) AS SupplyQty,
		--SUM(dd.[BargainTotal]) AS SupplyTotal,
		--SUM(dd.CostTotal) AS CostTotal,
		--SUM(dd.[BargainTotal]) AS SaleMoney,
		--SUM(dd.[taxtotal]) AS Taxtotal,
		--SUM(dd.[tax_total]) AS Tax_total,
		--SUM(dd.[total]) AS total,
		--SUM(dd.bargaintotal) AS BargainTotal,
		(dd.[qty]) AS SupplyQty,
        (dd.[BargainTotal]) AS SupplyTotal,
        (dd.CostTotal) AS CostTotal,
        (dd.[BargainTotal]) AS SaleMoney,
        (dd.[taxtotal]) AS Taxtotal,
        (dd.[tax_total]) AS Tax_total,
        (dd.[total]) AS total,
        (dd.bargaintotal) AS BargainTotal,
        dd.colorid,
        dd.sizeid,
        IfSupply,
        vchtype
INTO		#temp_data
FROM      (select Ptypeid,Dlyorder,IfSupply,vchtype from Dlydata s 
			where [DATE] between @szBeginData and @szEndData
			AND s.BillType = 2
			AND s.redold = 'F' AND EXISTS (SELECT 1 FROM #temp_p P WHERE p.TypeID = s.PtypeId)
			AND s.OpId = (CASE WHEN @OpID=0 THEN s.OpId ELSE @OpID END )				
			AND s.Dtypeid LIKE @Dtypeid + '%'
			AND s.Usedtype=CASE WHEN S.Vchtype IN ( 222, 224 ) THEN 1 ELSE s.Usedtype END
			AND (EXISTS ( SELECT 1 FROM   #TempBList FilterB WHERE  s.BtypeId = FilterB.TypeId ))
			AND (EXISTS ( SELECT 1 FROM #TempEList FilterE WHERE  s.EtypeId = FilterE.TypeId ))				
			AND (
               CustValue1 LIKE '%' + @SaleTraitName + '%'
              OR CustValue2 LIKE '%' + @SaleTraitName + '%'
              OR CustValue3 LIKE '%' + @SaleTraitName + '%'
              OR CustValue4 LIKE '%' + @SaleTraitName + '%'
              OR CustValue5 LIKE '%' + @SaleTraitName + '%'
              OR CustValue6 LIKE '%' + @SaleTraitName + '%'        
            ) 				
		AND EXISTS ( SELECT 1 FROM   #FilterKInfo FilterK WHERE  s.ktypeId = Filterk.KtypeId )
		--AND s.BranchId LIKE @BranchId + '%'
		AND EXISTS ( SELECT 1 FROM   #FilterVList FilterV WHERE  S.vchtype = FilterV.vchtype )
        AND EXISTS ( SELECT GetID FROM   #FilterVInfo FilterVch WHERE  S.VchType = FilterVch.GetID )  --单据类型                
			)S inner join 
        DlyDataDetail dd on s.dlyorder = dd.dlyorder

 --group by     Ptypeid, dd.colorid,
 --       dd.sizeid,
 --       IfSupply,
 --       vchtype


    SELECT  p.[typeid] AS ptypeid,
            SUM(qty) AS qty,
            SUM(Tqty) Tqty,
            SUM(TTotal) AS TTotal,
            SUM(qty) - SUM(Tqty) - SUM(Bqty) + SUM(ISNULL(SupplyQty, 0)) AS Sqty,
            SUM(Tax_total) AS tax_total,
            SUM(taxtotal) AS taxtotal,
            SUM(SaleMoney) AS STotal,
            SUM(STotal) AS Total,
            SUM(Total) - SUM(BargainTotal) AS ConvertTotal,
            SUM(SaleMoney) - SUM(Tax_total) AS DeductTotal,
            SUM(CostTotal) AS CostTotal,
            SUM(SaleMoney) - SUM(CostTotal) AS Profittotal,
            SUM(ISNULL(BQty, 0)) + SUM(Tqty) AS BSumQty,
            SUM(TTotal) + SUM(ISNULL(BTotal, 0)) AS BSumTotal,
            SUM(ISNULL(BQty, 0)) AS BQty,
            SUM(ISNULL(BTotal, 0)) AS BTotal,
            SUM(ISNULL(SupplyQty, 0)) AS SupplyQty,
            SUM(ISNULL(SupplyTotal, 0)) AS SupplyTotal,
            CAST(CAST(( CASE WHEN SUM(Total) = 0.00 THEN 0.00
                             ELSE ( SUM(Total) - SUM(BargainTotal) )
                                  / SUM(Total)
                        END * 100 ) AS NUMERIC(24, 2)) AS VARCHAR(30)) + '%' AS RLrate
    FROM    ( SELECT    p.[typeid],
                        ISNULL([Qty], 0) AS [Qty],
                        ISNULL([SaleMoney], 0) AS [SaleMoney],
                        ISNULL(Total, 0) AS Total,
                        ISNULL([taxtotal], 0) AS Taxtotal,
                        ISNULL([tax_total], 0) AS Tax_total,
                        ISNULL(BargainTotal, 0) AS BargainTotal,
                        p.porder,
                        ISNULL(Tqty, 0) AS Tqty,
                        ISNULL(TTotal, 0) AS TTotal,
                        ISNULL(STotal, 0) AS STotal,
                        ISNULL(CostTotal, 0) AS CostTotal,
                        ISNULL(BQty, 0) AS BQty,
                        ISNULL(BTotal, 0) AS BTotal,
                        ISNULL(SupplyQty, 0) AS SupplyQty,
                        ISNULL(SupplyTotal, 0) AS SupplyTotal
              FROM      #TempPtree p
                        LEFT JOIN ( SELECT  SUBSTRING(ptypeid, 1, LEN(@szptypeid) + 5) AS ptypeid,
                                            SUM(ISNULL(-qty, 0)) qty,
                                            SUM(ISNULL(-STotal, 0)) STotal,
                                            SUM(ISNULL(tqty, 0)) tqty,
                                            SUM(ISNULL(TTotal, 0)) TTotal,
                                            SUM(ISNULL(-salemoney, 0)) salemoney,
                                            SUM(ISNULL(-taxtotal, 0)) taxtotal,
                                            SUM(ISNULL(-Tax_total, 0)) Tax_total,
                                            SUM(ISNULL(-Total, 0)) Total,
                                            SUM(ISNULL(-BargainTotal, 0)) BargainTotal,
                                            SUM(ISNULL(-CostTotal, 0)) AS CostTotal,
                                            SUM(ISNULL(BQty, 0)) AS BQty,
                                            SUM(ISNULL(BTotal, 0)) AS BTotal,
                                            SUM(ISNULL(-SupplyQty, 0)) AS SupplyQty,
                                            SUM(ISNULL(-SupplyTotal, 0)) AS SupplyTotal
                                    FROM    ( SELECT    Ptypeid,           --销售数量(不包括补货)
                                                        SUM(ISNULL([Qty], 0)) AS [Qty],
                                                        SUM(ISNULL(STotal, 0)) AS STotal,
                                                        0 AS [TQty],
                                                        0 AS TTotal,
                                                        0 AS BQty,
                                                        0 AS BTotal,
                                                        0 AS SupplyQty,
                                                        0 AS SupplyTotal,
                                                        SUM(ISNULL(CostTotal, 0)) AS CostTotal,
                                                        SUM(ISNULL(SaleMoney, 0)) AS SaleMoney,
                                                        SUM(ISNULL(Taxtotal, 0)) AS Taxtotal,
                                                        SUM(ISNULL(Tax_total, 0)) AS Tax_total,
                                                        SUM(ISNULL(total, 0)) AS total,
                                                        SUM(ISNULL(BargainTotal, 0)) AS BargainTotal,
                                                        colorid,
                                                        sizeid
                                              FROM      #temp_data
                                              WHERE     qty < 0 AND ifSupply = 0
                                              GROUP BY  ptypeid, vchtype, colorid, sizeid
                                              UNION ALL
                                              SELECT    Ptypeid, --     补货数量
                                                        0 AS [Qty],
                                                        0 AS STotal,
                                                        0 AS [TQty],
                                                        0 AS TTotal,
                                                        0 AS BQty,
                                                        0 AS BTotal,
                                                        SUM(ISNULL(SupplyQty, 0)) AS SupplyQty,
                                                        SUM(ISNULL(SupplyTotal, 0)) AS SupplyTotal,
                                                        SUM(ISNULL(CostTotal, 0)) AS CostTotal,
                                                        SUM(ISNULL(SaleMoney, 0)) AS SaleMoney,
                                                        SUM(ISNULL(Taxtotal, 0)) AS Taxtotal,
                                                        SUM(ISNULL(Tax_total, 0)) AS Tax_total,
                                                        SUM(ISNULL(total, 0)) AS total,
                                                        SUM(ISNULL(BargainTotal, 0)) AS BargainTotal,
                                                        colorid,
                                                        sizeid
                                              FROM      #temp_data
                                              WHERE     qty < 0 AND ifSupply = 1 
                                              GROUP BY  ptypeid, vchtype, colorid, sizeid
                                              UNION ALL
                                              SELECT    Ptypeid,  --退货数量
                                                        0 AS [Qty],
                                                        0 AS STOtal,
                                                        SUM(ISNULL([TQty], 0)) AS [TQty],
                                                        SUM(ISNULL(TTotal, 0)) AS TTotal,
                                                        0 AS BQty,
                                                        0 AS BTotal,
                                                        0 AS SupplyQty,
                                                        0 AS SupplyTotal,
                                                        SUM(ISNULL(CostTotal, 0)) AS CostTotal,
                                                        SUM(ISNULL(SaleMoney, 0)) AS SaleMoney,
                                                        SUM(ISNULL(Taxtotal, 0)) AS Taxtotal,
                                                        SUM(ISNULL(Tax_total, 0)) AS Tax_total,
                                                        SUM(ISNULL(total, 0)) AS total,
                                                        SUM(ISNULL(BargainTotal, 0)) AS BargainTotal,
                                                        colorid,
                                                        sizeid
                                              FROM      #temp_data
                                              WHERE     qty > 0
                                              GROUP BY  ptypeid, vchtype, colorid, sizeid
                                            ) C
                                    GROUP BY SUBSTRING(ptypeid, 1, LEN(@szptypeid) + 5)
                                  ) Salebill ON p.[typeid] = Salebill.ptypeid
	            ) p
	    GROUP BY [typeid],
	             p.porder
    ORDER BY p.porder,
             p.[typeid]
	
    if object_id('tempdb..#FilterK') is not null 
        drop table #FilterK       
    if object_id('tempdb..#TempAllJXC2') is not null 
        drop table #TempAllJXC2       
    if object_id('tempdb..#TempAllJXC2q') is not null 
        drop table #TempAllJXC2q                      
    if object_id('tempdb..#TempAllJXC3') is not null 
        drop table #TempAllJXC3       
    IF OBJECT_ID('tempdb..#TempBList') IS NOT NULL 
        DROP TABLE #TempBList        
    IF OBJECT_ID('tempdb..#TempEList') IS NOT NULL 
        DROP TABLE #TempEList                    
GO
 SET QUOTED_IDENTIFIER OFF 
GO
 SET ANSI_NULLS ON 
GO





/**/
/******************************************20131022********************************************/
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZSaleAnalyseListCS_BS]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZSaleAnalyseListCS_BS]
GO

/*
  作者:QF
  时间:2011-08-24			
  主要内容:功能增加 发货类型、退货类型
  时间:2011-09-15			
  主要内容:更改BUG,原BarTerType=0表示正常退货，现改为服装CS独用,服装BS用OpID【次品退货同理】
  时间:2011-09-19			
  主要内容:BS端，退货方式分为[正常退货,次品退货,其他退货等等]，由于合并相对麻烦，分开为宜

*/

CREATE PROCEDURE FZSaleAnalyseListCS_BS
    (
      @szPtypeId VARCHAR(50),
      @szKtypeid VARCHAR(2000),
      @szBtypeid VARCHAR(50),
      @szBeginData VARCHAR(50),
      @szEndData VARCHAR(50),
      @ifstop VARCHAR(2),
      @attrib1 INT = -1,
      @attrib2 INT = -1,
      @attrib3 INT = -1,
      @attrib4 INT = -1,
      @Assist1TypeID INT = -1,
      @Assist2TypeID INT = -1,
      @Assist3TypeID INT = -1,
      @Assist4TypeID INT = -1,
      @Sizeid VARCHAR(4) = '',
      @Colorid VARCHAR(4) = '',
      @Etypeid VARCHAR(50),
      @SaleTraitname VARCHAR(1000),
      @Dtypeid VARCHAR(50),
      @CustType VARCHAR(10),
      @branchid VARCHAR(2000),
      @vchtype VARCHAR(100), --单据类型  
      @OperatorId VARCHAR(50) ,
	@OpID		INT = 0   --0-全部 , 其他为具体类型 
    )
AS 
DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output  
 

    DECLARE @tempPtypeID VARCHAR(50)  
    SET @tempPtypeID = @szPtypeId

    DECLARE @ptypeid_sale VARCHAR(50)
    SET @ptypeid_sale = @szPtypeId
    IF @SaleTraitName = '全部' 
        SET @SaleTraitName = '' 
    IF @ptypeid_sale IS NULL
        OR @ptypeid_sale = '' 
        SET @ptypeid_sale = '0'
    IF @szPtypeId IS NULL
        OR @szPtypeId = '' 
        SET @szPtypeId = '%'
    IF @Colorid IS NULL
        OR @Colorid = ''
        OR @Colorid = '0' 
        SET @Colorid = '%'
    IF @Sizeid IS NULL
        OR @Sizeid = ''
        OR @Sizeid = '0' 
        SET @Sizeid = '%'
    IF @branchid = ',' 
        SET @branchid = ''
--总部和加盟商共用一个，当不进行筛选单据的情况下，要把单据范围补齐
    IF LEFT(@branchid, 5) = '00001' OR @branchid = ''
        BEGIN
            IF @vchtype IS NULL
                OR @vchtype = '' 
                SET @vchtype = '100,11,45,24,12,222,224'	--总部统计的销售主体单据
        END
    ELSE 
        BEGIN
            IF @vchtype IS NULL
                OR @vchtype = '' 
                SET @vchtype = '11,12,45,24'			--加盟商统计的销售主体单据
        END
	declare @tembranchid varchar(50)
	SET @tembranchid =LEFT(@branchid,50)      
	
	
		IF object_id('tempdb..#P') is not null  
			drop table #P
		IF object_id('tempdb..#b') is not null  
			drop table #b
		IF object_id('tempdb..#e') is not null  
			drop table #e
		IF object_id('tempdb..#br') is not null  
			drop table #br
		
		SELECT TypeId INTO #P FROM  FN_GetPowerRangePList(@OperatorId, @szPtypeID)
		SELECT Typeid INTO #b FROM  FN_GetPowerRangeBList(@OperatorId, @szBtypeid, '2,3,4,6')
		SELECT Typeid INTO #e FROM  FN_GetPowerRangeEList(@OperatorId, @EtypeID)
		SELECT KtypeId,selfhelp INTO #br FROM  FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid)

		CREATE CLUSTERED INDEX I_p_typeid ON #P(TypeId)
		CREATE CLUSTERED INDEX I_e_typeid ON #e(TypeId)
		CREATE CLUSTERED INDEX I_b_typeid ON #b(TypeId)
		CREATE CLUSTERED INDEX I_br_typeid ON #br(KtypeId)  
		
		SELECT GetID INTO #Vlist FROM  FN_GetIdStrListTable(@vchtype)
---------------
  SELECT    Ptypeid,  
            dd.[qty] AS [Qty],
            dd.[BargainTotal] AS STotal,
            dd.[qty] AS [TQty],
            dd.[BargainTotal] AS TTotal,
            0 AS BQty,
            0 AS BTotal,
			dd.[qty] AS SupplyQty,
            dd.[BargainTotal] AS SupplyTotal,
            dd.CostTotal AS CostTotal,
            dd.[BargainTotal] AS SaleMoney,
            dd.[taxtotal] AS Taxtotal,
            dd.[tax_total] AS Tax_total,
            dd.[total] AS total,
            dd.bargaintotal AS BargainTotal,
            dd.colorid,
            dd.sizeid,
            IfSupply,
            vchtype
  INTO		#temp_data
  FROM      Dlydata S,  
            DlyDataDetail dd
  WHERE     S.[date] BETWEEN @szBeginData AND @szEndData 
            AND s.BillType = 2
            AND s.redold = 'F' 
            AND s.dlyorder = dd.dlyorder
			AND s.OpId = (CASE WHEN @OpID=0 THEN s.OpId ELSE @OpID END )
            AND s.usedtype = CASE WHEN s.vchtype IN ( 222, 224 ) THEN 1 ELSE s.usedtype END
            AND EXISTS ( SELECT 1 FROM   GetKtypeIdTable(@szKtypeid, @BranchId) b WHERE  s.KtypeId = b.KtypeId )
            AND s.Dtypeid LIKE @Dtypeid + '%'		--ljh add: 2011-01-24
			AND ( EXISTS ( SELECT 1 FROM  #P FilterP WHERE  s.PtypeId = FilterP.TypeId ))
			AND (EXISTS ( SELECT 1 FROM   #b FilterB WHERE  s.BtypeId = FilterB.TypeId ))
			AND (EXISTS ( SELECT 1 FROM   #e FilterE WHERE  s.EtypeId = FilterE.TypeId ))
			AND EXISTS ( SELECT 1 FROM   #br FilterK WHERE  s.ktypeId = Filterk.KtypeId )
			--AND s.BranchId LIKE @BranchId + '%'
			AND EXISTS ( SELECT 1 FROM   FN_GetPowerRangeVList(@tembranchid) FilterV WHERE  S.vchtype = FilterV.vchtype )
            AND EXISTS ( SELECT GetID FROM  #Vlist FilterVch WHERE  S.VchType = FilterVch.GetID )  --单据类型
            AND ( CustValue1 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue2 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue3 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue4 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue5 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue6 LIKE '%' + @SaleTraitName + '%'
                ) 
            AND dd.sizeid = (CASE WHEN @Sizeid = '%' THEN dd.sizeid ELSE @Sizeid END)
            AND dd.colorid = (CASE WHEN @colorid = '%'THEN dd.colorid ELSE @colorid END) 
---------------
    SELECT  p.[typeid] AS ptypeid,
            ( qty ) AS qty,
            ( Tqty ) Tqty,
            ( TTotal ) AS TTotal,
            ( qty ) - ( Tqty ) - ( Bqty ) + ( ISNULL(SupplyQty, 0) ) AS Sqty,
            ( Tax_total ) AS tax_total,
            ( taxtotal ) AS taxtotal,
            ( SaleMoney ) AS sTotal,
            ( sTotal ) AS Total,
            ( Total ) - ( BargainTotal ) AS ConvertTotal,
            ( SaleMoney ) - ( Tax_total ) AS DeductTotal,
            p.RetailPrice,
            ( ISNULL(BQty, 0) ) + ( Tqty ) AS BSumQty,
            ( TTotal ) + ( ISNULL(BTotal, 0) ) AS BSumTotal,
            ROUND(( Qty + SupplyQty - TQty) * RetailPrice,@dig_total) AS RetailTotal, 
            ( SaleMoney ) - ( CostTotal ) AS Profittotal,
            ( ISNULL(BQty, 0) ) AS BQty,
            ( ISNULL(BTotal, 0) ) AS BTotal,
            ( ISNULL(SupplyQty, 0) ) AS SupplyQty,
            ( ISNULL(SupplyTotal, 0) ) AS SupplyTotal,
            ( CostTotal ) AS CostTotal,
            RIGHT('00000' + CAST(p.colorid AS VARCHAR), 5) AS pctypeid,
            RIGHT('00000' + CAST(p.sizeid AS VARCHAR), 5) AS pstypeid,
	    (SELECT [Order] FROM [Size] si WHERE si.SizeId = p.sizeid ) as psOrder ,
            CAST(CAST(( CASE WHEN ( Total ) = 0 THEN 0
                             ELSE ( ( Total ) - ( BargainTotal ) ) / ( Total )
                        END ) * 100 AS NUMERIC(24, 2)) AS VARCHAR(30)) + '%' AS RLrate
    FROM    ( SELECT    p1.[typeid],
                        porder,
                        RetailPrice,
                        c.sizeid,
                        b.colorid
              FROM      ( SELECT    typeid,
                                    porder,
                                    retailprice
                          FROM      FN_GetPowerRangePList(@OperatorId, @tempPtypeID)--ptype    
                          WHERE     [typeid] <> '00000'
                                    AND stop = CASE @ifstop WHEN '0' THEN '0' ELSE stop END
                                    AND (parid LIKE @szPtypeId + '%' OR  typeid = @szPtypeid)
                        ) p1
                        LEFT JOIN ( SELECT  a.ptypeid,
                                            a.attributeid,
                                            b.typeid
                                    FROM    ptypeattribute a,
                                            assistattribute b
                                    WHERE   a.attributeid = b.attributeid
                                            AND b.typeid = @Assist1TypeID
                                  ) ls1 ON @attrib1 <> -1
                                           AND ls1.ptypeid = p1.typeid
                        LEFT JOIN ( SELECT  a.ptypeid,
                                            a.attributeid,
                                            b.typeid
                                    FROM    ptypeattribute a,
                                            assistattribute b
                                    WHERE   a.attributeid = b.attributeid
                                            AND b.typeid = @Assist2TypeID
                                  ) ls2 ON @attrib2 <> -1
                                           AND ls2.ptypeid = p1.typeid
                        LEFT JOIN ( SELECT  a.ptypeid,
                                            a.attributeid,
                                            b.typeid
                                    FROM    ptypeattribute a,
                                            assistattribute b
                                    WHERE   a.attributeid = b.attributeid
                                            AND b.typeid = @Assist3TypeID
                                  ) ls3 ON @attrib3 <> -1
                                           AND ls3.ptypeid = p1.typeid
                        LEFT JOIN ( SELECT  a.ptypeid,
                                            a.attributeid,
                                            b.typeid
                                    FROM    ptypeattribute a,
                                            assistattribute b
                                    WHERE   a.attributeid = b.attributeid
                                            AND b.typeid = @Assist4TypeID
                                  ) ls4 ON @attrib4 <> -1
                                           AND ls4.ptypeid = p1.typeid
                        LEFT JOIN ptypecolor b ON p1.typeid = b.ptypeid
                        LEFT JOIN ptypesize c ON p1.typeid = c.ptypeid
              WHERE     ISNULL(ls1.attributeid, -1) = CASE WHEN @attrib1 = -1
                                                           THEN ISNULL(ls1.attributeid, -1)
                                                           ELSE @attrib1
                                                      END
                        AND ISNULL(ls2.attributeid, -1) = CASE WHEN @attrib2 = -1 THEN ISNULL(ls2.attributeid, -1)
                                                               ELSE @attrib2
                                                          END
                        AND ISNULL(ls3.attributeid, -1) = CASE WHEN @attrib3 = -1 THEN ISNULL(ls3.attributeid, -1)
                                                               ELSE @attrib3
                                                          END
                        AND ISNULL(ls4.attributeid, -1) = CASE WHEN @attrib4 = -1 THEN ISNULL(ls4.attributeid, -1)
                                                               ELSE @attrib4
                                                          END
            ) p,
            ( SELECT    Ptypeid AS ptypeid,
                        SUM(ISNULL(-qty, 0)) qty,
                        SUM(ISNULL(-STotal, 0)) STotal,
                        SUM(ISNULL(tqty, 0)) tqty,
                        SUM(ISNULL(TTotal, 0)) TTotal,
                        SUM(ISNULL(-salemoney, 0)) salemoney,
                        SUM(ISNULL(-taxtotal, 0)) taxtotal,
                        SUM(ISNULL(-Tax_total, 0)) Tax_total,
                        SUM(ISNULL(-Total, 0)) Total,
                        SUM(ISNULL(-BargainTotal, 0)) BargainTotal,
                        SUM(ISNULL(-CostTotal, 0)) AS CostTotal,
                        SUM(ISNULL(BQty, 0)) AS BQty,
                        SUM(ISNULL(BTotal, 0)) AS BTotal,
                        SUM(ISNULL(-SupplyQty, 0)) AS SupplyQty,
                        SUM(ISNULL(-SupplyTotal, 0)) AS SupplyTotal,
                        colorid,
                        sizeid
              FROM      ( SELECT    Ptypeid,           --销售数量(不包括补货)
                                                        SUM(ISNULL([Qty], 0)) AS [Qty],
                                                        SUM(ISNULL(STotal, 0)) AS STotal,
                                                        0 AS [TQty],
                                                        0 AS TTotal,
                                                        0 AS BQty,
                                                        0 AS BTotal,
                                                        0 AS SupplyQty,
                                                        0 AS SupplyTotal,
                                                        SUM(ISNULL(CostTotal, 0)) AS CostTotal,
                                                        SUM(ISNULL(SaleMoney, 0)) AS SaleMoney,
                                                        SUM(ISNULL(Taxtotal, 0)) AS Taxtotal,
                                                        SUM(ISNULL(Tax_total, 0)) AS Tax_total,
                                                        SUM(ISNULL(total, 0)) AS total,
                                                        SUM(ISNULL(BargainTotal, 0)) AS BargainTotal,
                                                        colorid,
                                                        sizeid
                                              FROM      #temp_data
                                              WHERE     qty < 0 AND ifSupply = 0
                                              GROUP BY  ptypeid, vchtype, colorid, sizeid
                                              UNION ALL
                                              SELECT    Ptypeid, --     补货数量
                                                        0 AS [Qty],
                                                        0 AS STotal,
                                                        0 AS [TQty],
                                                        0 AS TTotal,
                                                        0 AS BQty,
                                                        0 AS BTotal,
                                                        SUM(ISNULL(SupplyQty, 0)) AS SupplyQty,
                                                        SUM(ISNULL(SupplyTotal, 0)) AS SupplyTotal,
                                                        SUM(ISNULL(CostTotal, 0)) AS CostTotal,
                                                        SUM(ISNULL(SaleMoney, 0)) AS SaleMoney,
                                                        SUM(ISNULL(Taxtotal, 0)) AS Taxtotal,
                                                        SUM(ISNULL(Tax_total, 0)) AS Tax_total,
                                                        SUM(ISNULL(total, 0)) AS total,
                                                        SUM(ISNULL(BargainTotal, 0)) AS BargainTotal,
                                                        colorid,
                                                        sizeid
                                              FROM      #temp_data
                                              WHERE     qty < 0 AND ifSupply = 1 
                                              GROUP BY  ptypeid, vchtype, colorid, sizeid
                                              UNION ALL
                                              SELECT    Ptypeid,  --退货数量
                                                        0 AS [Qty],
                                                        0 AS STOtal,
                                                        SUM(ISNULL([TQty], 0)) AS [TQty],
                                                        SUM(ISNULL(TTotal, 0)) AS TTotal,
                                                        0 AS BQty,
                                                        0 AS BTotal,
                                                        0 AS SupplyQty,
                                                        0 AS SupplyTotal,
                                                        SUM(ISNULL(CostTotal, 0)) AS CostTotal,
                                                        SUM(ISNULL(SaleMoney, 0)) AS SaleMoney,
                                                        SUM(ISNULL(Taxtotal, 0)) AS Taxtotal,
                                                        SUM(ISNULL(Tax_total, 0)) AS Tax_total,
                                                        SUM(ISNULL(total, 0)) AS total,
                                                        SUM(ISNULL(BargainTotal, 0)) AS BargainTotal,
                                                        colorid,
                                                        sizeid
                                              FROM      #temp_data
                                              WHERE     qty > 0
                                              GROUP BY  ptypeid, vchtype, colorid, sizeid
                                            ) C
              GROUP BY  ptypeid,
                        colorid,
                        sizeid
            ) Salebill
    WHERE   p.[typeid] = Salebill.ptypeid
            AND p.sizeid = salebill.sizeid
            AND p.colorid = salebill.colorid
    ORDER BY p.porder, p.[typeid] , p.colorId ,psOrder,p.sizeId 
	
	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZSaleAnalyseList_BS]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZSaleAnalyseList_BS]
GO

/*
  作者:QF
  时间:2011-08-24			
  主要内容:功能增加 发货类型、退货类型
  时间:2011-09-15			
  主要内容:更改BUG,原BarTerType=0表示正常退货，现改为服装CS独用,服装BS用OpID【次品退货同理】

*/

CREATE PROCEDURE FZSaleAnalyseList_BS
    (
      @szPtypeId VARCHAR(50),
      @szKtypeid VARCHAR(2000),
      @szBtypeid VARCHAR(50),
      @szBeginData VARCHAR(50),
      @szEndData VARCHAR(50),
      @ifstop VARCHAR(2),
      @attrib1 INT = -1,
      @attrib2 INT = -1,
      @attrib3 INT = -1,
      @attrib4 INT = -1,
      @Assist1TypeID INT = -1,
      @Assist2TypeID INT = -1,
      @Assist3TypeID INT = -1,
      @Assist4TypeID INT = -1,
      @Etypeid VARCHAR(50),
      @SaleTraitname VARCHAR(1000),
      @Dtypeid VARCHAR(50),
      @CustType VARCHAR(10),
      @branchid VARCHAR(2000),
      @vchtype VARCHAR(100),	--单据类型
      @OperatorId VARCHAR(50) ,
	@OpID		INT = 0   --0-全部 , 其他为具体类型 
    )
AS 
DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output  

    IF @SaleTraitName = '全部' 
        SET @SaleTraitName = ''

    DECLARE @tempPtypeID VARCHAR(50)
    SET @tempPtypeID = @szPtypeId

    IF @szPtypeId IS NULL
        OR @szPtypeId = '' 
        SET @szPtypeId = '%'

--总部和加盟商共用一个，当不进行筛选单据的情况下，要把单据范围补齐
    IF LEFT(@branchid, 5) = '00001' 
        BEGIN
            IF @vchtype IS NULL
                OR @vchtype = '' 
                SET @vchtype = '100,11,45,24,12,222,224'	--总部统计的销售主体单据
        END
    ELSE 
        BEGIN
            IF @vchtype IS NULL
                OR @vchtype = '' 
                SET @vchtype = '11,12,45,24'			--加盟商统计的销售主体单据
        END
        
        declare @tembranchid varchar(50)
	SET @tembranchid =LEFT(@branchid,50)
	
	
		IF object_id('tempdb..#P') is not null  
			drop table #P
		IF object_id('tempdb..#b') is not null  
			drop table #b
		IF object_id('tempdb..#e') is not null  
			drop table #e
		IF object_id('tempdb..#br') is not null  
			drop table #br
		SELECT TypeId,porder,[stop] INTO #P FROM  FN_GetPowerRangePList(@OperatorId, @tempPtypeID)
		SELECT Typeid INTO #b FROM  FN_GetPowerRangeBList(@OperatorId, @szBtypeid, '2,3,4,6')
		SELECT Typeid INTO #e FROM  FN_GetPowerRangeEList(@OperatorId, @EtypeID)
		SELECT KtypeId,selfhelp INTO #br FROM  FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid)

		CREATE CLUSTERED INDEX I_p_typeid ON #P(TypeId)
		CREATE CLUSTERED INDEX I_e_typeid ON #e(TypeId)
		CREATE CLUSTERED INDEX I_b_typeid ON #b(TypeId)
		CREATE CLUSTERED INDEX I_br_typeid ON #br(KtypeId)
		
		SELECT GetID INTO #Vlist FROM  FN_GetIdStrListTable(@vchtype)
---------------
      SELECT    Ptypeid, --     补货数量
                dd.[qty] AS [Qty],
                dd.[BargainTotal] AS STotal,
                dd.[qty] AS [TQty],
                dd.[BargainTotal] AS TTotal,
                0 AS BQty,
                0 AS BTotal,
                dd.[qty] AS SupplyQty,
                dd.[BargainTotal] AS SupplyTotal,
                dd.CostTotal AS CostTotal,
                dd.[BargainTotal] AS SaleMoney,
                dd.[taxtotal] AS Taxtotal,
                dd.[tax_total] AS Tax_total,
                dd.[total] AS total,
                dd.bargaintotal AS BargainTotal,
                RetailPrice AS RetailPrice,
                dd.colorid,
                dd.sizeid,
                IfSupply,
                Vchtype
	  INTO		#temp_data                
      FROM      Dlydata S,
                DlyDataDetail dd
      WHERE     S.[date] BETWEEN @szBeginData AND @szEndData
                AND s.billtype = 2
                AND s.redold = 'F'
                AND s.dlyorder = dd.dlyorder 
				AND s.OpId = (CASE WHEN @OpID=0 THEN s.OpId ELSE @OpID END ) 
                AND s.usedtype = CASE WHEN s.vchtype IN ( 222, 224 ) THEN 1 ELSE s.usedtype END
                AND s.Dtypeid LIKE @Dtypeid + '%'
                AND EXISTS ( SELECT GetID FROM  #Vlist FilterVch WHERE  s.VchType = FilterVch.GetID )--加的单据类型筛选
				AND (EXISTS ( SELECT 1 FROM   #P FilterP WHERE  s.PtypeId = FilterP.TypeId ))
				AND (EXISTS ( SELECT 1 FROM   #b FilterB WHERE  s.BtypeId = FilterB.TypeId ))
				AND (EXISTS ( SELECT 1 FROM   #e FilterE WHERE  s.EtypeId = FilterE.TypeId ))
				AND (EXISTS ( SELECT 1 FROM   #br FilterK WHERE  s.ktypeId = Filterk.KtypeId ))
				--AND s.BranchId LIKE @BranchId + '%'
				AND EXISTS ( SELECT 1 FROM   FN_GetPowerRangeVList(@tembranchid) FilterV WHERE  S.vchtype = FilterV.vchtype )
                AND ( CustValue1 LIKE '%' + @SaleTraitName + '%'
                      OR CustValue2 LIKE '%' + @SaleTraitName + '%'
                      OR CustValue3 LIKE '%' + @SaleTraitName + '%'
                      OR CustValue4 LIKE '%' + @SaleTraitName + '%'
                      OR CustValue5 LIKE '%' + @SaleTraitName + '%'
                      OR CustValue6 LIKE '%' + @SaleTraitName + '%'
                    )
                    
--------------------                    
	  SELECT    p1.[typeid], porder
	  INTO      #tmp_ptype
      FROM      #P p1
                LEFT JOIN ( SELECT  a.ptypeid,
                                    a.attributeid,
                                    b.typeid
                            FROM    ptypeattribute a,
                                    assistattribute b
                            WHERE   a.attributeid = b.attributeid
                                    AND typeid = @Assist1TypeID
                          ) ls1 ON @attrib1 <> -1
                                   AND ls1.ptypeid = p1.typeid
                LEFT JOIN ( SELECT  a.ptypeid,
                                    a.attributeid,
                                    b.typeid
                            FROM    ptypeattribute a,
                                    assistattribute b
                            WHERE   a.attributeid = b.attributeid
                                    AND typeid = @Assist2TypeID
                          ) ls2 ON @attrib2 <> -1
                                   AND ls2.ptypeid = p1.typeid
                LEFT JOIN ( SELECT  a.ptypeid,
                                    a.attributeid,
                                    b.typeid
                            FROM    ptypeattribute a,
                                    assistattribute b
                            WHERE   a.attributeid = b.attributeid
                                    AND typeid = @Assist3TypeID
                          ) ls3 ON @attrib3 <> -1
                                   AND ls3.ptypeid = p1.typeid
                LEFT JOIN ( SELECT  a.ptypeid,
                                    a.attributeid,
                                    b.typeid
                            FROM    ptypeattribute a,
                                    assistattribute b
                            WHERE   a.attributeid = b.attributeid
                                    AND typeid = @Assist4TypeID
                          ) ls4 ON @attrib4 <> -1
                                   AND ls4.ptypeid = p1.typeid
        WHERE     (@ifstop <> 0 OR p1.STOP = 0) 
		AND (@attrib1 = -1 OR ISNULL(ls1.attributeid, -1) = @attrib1)
		AND (@attrib2 = -1 OR ISNULL(ls2.attributeid, -1) = @attrib2)
		AND (@attrib3 = -1 OR ISNULL(ls3.attributeid, -1) = @attrib3)
		AND (@attrib4 = -1 OR ISNULL(ls4.attributeid, -1) = @attrib4)
		
		CREATE CLUSTERED INDEX I_tmp_typeid ON #tmp_ptype(TypeId)
---------------
    SELECT  ptypeid,
            SUM(qty) AS qty,
            SUM(Tqty) Tqty,
            SUM(TTotal) AS TTotal,
            SUM(qty) - SUM(Tqty) - SUM(Bqty) + SUM(ISNULL(SupplyQty, 0)) AS Sqty,
            SUM(Tax_total) AS tax_total,
            SUM(taxtotal) AS taxtotal,
            SUM(SaleMoney) AS sTotal,
            SUM(sTotal) AS Total,
            SUM(Total) - SUM(BargainTotal) AS ConvertTotal,
            SUM(SaleMoney) - SUM(Tax_total) AS DeductTotal,
            SUM(RetailTotal) AS RetailTotal,
            SUM(SaleMoney) - SUM(CostTotal) AS Profittotal,
            SUM(ISNULL(BQty, 0)) + SUM(Tqty) AS BSumQty,
            SUM(TTotal) + SUM(ISNULL(BTotal, 0)) AS BSumTotal,
            SUM(ISNULL(BQty, 0)) AS BQty,
            SUM(ISNULL(BTotal, 0)) AS BTotal,
            SUM(ISNULL(SupplyQty, 0)) AS SupplyQty,
            SUM(ISNULL(SupplyTotal, 0)) AS SupplyTotal,
            SUM(CostTotal) AS CostTotal,
            CAST(CAST(( CASE WHEN SUM(Total) = 0 THEN 0
                             ELSE ( SUM(Total) - SUM(BargainTotal) )
                                  / SUM(Total)
                        END ) * 100 AS NUMERIC(24, 2)) AS VARCHAR(30)) + '%' AS RLrate
    FROM    ( SELECT    ptypeid,
                        ISNULL([Qty], 0) AS [Qty],
                        ISNULL([SaleMoney], 0) AS [SaleMoney],
                        ISNULL(Total, 0) AS Total,
                        ISNULL([taxtotal], 0) AS Taxtotal,
                        ISNULL([tax_total], 0) AS Tax_total,
                        ISNULL(BargainTotal, 0) AS BargainTotal,
                        porder,
                        ISNULL(Tqty, 0) AS Tqty,
                        ISNULL(TTotal, 0) AS TTotal,
                        ISNULL(STotal, 0) AS STotal,
                        ISNULL(CostTotal, 0) AS CostTotal,
                        ISNULL(BQty, 0) AS BQty,
                        ISNULL(BTotal, 0) AS BTotal,
                        ISNULL(SupplyQty, 0) AS SupplyQty,
                        ISNULL(SupplyTotal, 0) AS SupplyTotal,
                        ISNULL(RetailTotal, 0) AS RetailTotal
              FROM       
              
								  ( SELECT  Ptypeid AS ptypeid,
                                            SUM(ISNULL(-qty, 0)) qty,
                                            SUM(ISNULL(-STotal, 0)) STotal,
                                            SUM(ISNULL(tqty, 0)) tqty,
                                            SUM(ISNULL(TTotal, 0)) TTotal,
                                            SUM(ISNULL(-salemoney, 0)) salemoney,
                                            SUM(ISNULL(-taxtotal, 0)) taxtotal,
                                            SUM(ISNULL(-Tax_total, 0)) Tax_total,
                                            SUM(ISNULL(-Total, 0)) Total,
                                            SUM(ISNULL(-BargainTotal, 0)) BargainTotal,
                                            SUM(ISNULL(-CostTotal, 0)) AS CostTotal,
                                            SUM(ISNULL(BQty, 0)) AS BQty,
                                            SUM(ISNULL(BTotal, 0)) AS BTotal,
                                            SUM(ISNULL(-SupplyQty, 0)) AS SupplyQty,
                                            SUM(ISNULL(-SupplyTotal, 0)) AS SupplyTotal,
                                            SUM(ISNULL(-RetailTotal, 0)) AS RetailTotal,
                                            porder
                                    FROM    ( SELECT    Ptypeid,           --销售数量(不包括补货)
                                                        SUM(ISNULL([Qty], 0)) AS [Qty],
                                                        SUM(ISNULL(STotal, 0)) AS STotal,
                                                        0 AS [TQty],
                                                        0 AS TTotal,
                                                        0 AS BQty,
                                                        0 AS BTotal,
                                                        0 AS SupplyQty,
                                                        0 AS SupplyTotal,
                                                        SUM(ISNULL(CostTotal, 0)) AS CostTotal,
                                                        SUM(ISNULL(SaleMoney, 0)) AS SaleMoney,
                                                        SUM(ISNULL(Taxtotal, 0)) AS Taxtotal,
                                                        SUM(ISNULL(Tax_total, 0)) AS Tax_total,
                                                        SUM(ISNULL(total, 0)) AS total,
                                                        SUM(ISNULL(BargainTotal, 0)) AS BargainTotal,
                                                        ROUND(SUM(ISNULL([qty], 0) * RetailPrice),@dig_total) AS RetailTotal,
                                                        colorid,
                                                        sizeid,
                                                        porder
                                              FROM      #temp_data,#tmp_ptype
                                              WHERE     ifSupply = 0 AND qty < 0 AND #tmp_ptype.TypeID = #temp_data.ptypeid
                                              GROUP BY  ptypeid, vchtype, colorid, sizeid, porder
                                              UNION ALL
                                              SELECT    Ptypeid, --     补货数量
                                                        0 AS [Qty],
                                                        0 AS STotal,
                                                        0 AS [TQty],
                                                        0 AS TTotal,
                                                        0 AS BQty,
                                                        0 AS BTotal,
                                                        SUM(ISNULL(SupplyQty, 0)) AS SupplyQty,
                                                        SUM(ISNULL(SupplyTotal, 0)) AS SupplyTotal,
                                                        SUM(ISNULL(CostTotal, 0)) AS CostTotal,
                                                        SUM(ISNULL(SaleMoney, 0)) AS SaleMoney,
                                                        SUM(ISNULL(Taxtotal, 0)) AS Taxtotal,
                                                        SUM(ISNULL(Tax_total, 0)) AS Tax_total,
                                                        SUM(ISNULL(total, 0)) AS total,
                                                        SUM(ISNULL(bargaintotal, 0)) AS BargainTotal,
                                                        ROUND(SUM(ISNULL([qty], 0) * RetailPrice),@dig_total) AS RetailTotal,
                                                        colorid,
                                                        sizeid,
                                                        porder
                                              FROM      #temp_data,#tmp_ptype
                                              WHERE     ifSupply = 1 AND qty < 0 AND #tmp_ptype.TypeID = #temp_data.ptypeid
                                              GROUP BY  ptypeid, vchtype, colorid, sizeid, porder
                                              UNION ALL
                                              SELECT    Ptypeid,  -- 退货数量
                                                        0 AS [Qty],
                                                        0 AS STOtal,
                                                        SUM(ISNULL([TQty], 0)) AS [TQty],
                                                        SUM(ISNULL(TTotal, 0)) AS TTotal,
                                                        0 AS BQty,
                                                        0 AS BTotal,
                                                        0 AS SupplyQty,
                                                        0 AS SupplyTotal,
                                                        SUM(ISNULL(CostTotal, 0)) AS CostTotal,
                                                        SUM(ISNULL(SaleMoney, 0)) AS SaleMoney,
                                                        SUM(ISNULL(Taxtotal, 0)) AS Taxtotal,
                                                        SUM(ISNULL(Tax_total, 0)) AS Tax_total,
                                                        SUM(ISNULL(total, 0)) AS total,
                                                        SUM(ISNULL(BargainTotal, 0)) AS BargainTotal,
                                                        ROUND(SUM(ISNULL([qty], 0) * RetailPrice),@dig_total) AS RetailTotal,
                                                        colorid,
                                                        sizeid,
                                                        porder
                                              FROM      #temp_data,#tmp_ptype
                                              WHERE     qty > 0 AND #tmp_ptype.TypeID = #temp_data.ptypeid
                                              GROUP BY  ptypeid, vchtype, colorid, sizeid, porder
                                            ) C
                                    GROUP BY ptypeid,porder
                                  ) Salebill  
	            ) p
	    GROUP BY ptypeid, porder
    ORDER BY porder, 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].[FZBtypeSaleAnalyseList_BS]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZBtypeSaleAnalyseList_BS]
GO

/*
  作者:QF
  时间:2011-09-19			
  主要内容:BS端，退货方式分为[正常退货,次品退货,其他退货等等]，由于合并相对麻烦，分开为宜

*/


CREATE PROCEDURE FZBtypeSaleAnalyseList_BS
    (
      @szPtypeId VARCHAR(50) ,
      @szKtypeid VARCHAR(50) ,
      @szBtypeid VARCHAR(50) ,
      @szBeginData VARCHAR(50) ,
      @szEndData VARCHAR(50) ,
      @ifstop VARCHAR(2) ,
      @attrib1 INT = -1 ,
      @attrib2 INT = -1 ,
      @attrib3 INT = -1 ,
      @attrib4 INT = -1 ,
      @Assist1TypeID INT = -1 ,
      @Assist2TypeID INT = -1 ,
      @Assist3TypeID INT = -1 ,
      @Assist4TypeID INT = -1 ,
      @Etypeid VARCHAR(50) ,
      @Dtypeid VARCHAR(50) ,
      @A1 VARCHAR(8000) = '' ,--品牌  
      @A2 VARCHAR(8000) = '' ,--季节  
      @A3 VARCHAR(8000) = '' ,--辅助属性1  
      @A4 VARCHAR(8000) = '' ,--辅助属性2   	
      @branchid VARCHAR(50) ,
      @OperatorId VARCHAR(50) = '00000' ,
      @OpID INT = 0   --0-全部 , 其他为具体类型 
    )
AS 

    DECLARE @OperatorIsJM BIT
    SELECT  @OperatorIsJM = SelfHelp
    FROM    Branch a
            LEFT JOIN Employee b ON a.branchid = b.branchid
    WHERE   b.typeid = @OperatorId

    IF OBJECT_ID('tempdb..#TmpP') IS NOT NULL 
        DROP TABLE #TmpP
    CREATE TABLE #TmpP ( PTypeID VARCHAR(50) )
    DECLARE @singlePtypeid INT
-- @A2 季节
    IF @A2 = '' 
        BEGIN
            INSERT  INTO #TmpP ( PTypeID )
                    SELECT  TypeId
                    FROM    dbo.FN_GetPowerRangePList(@Operatorid, '%')
        END
    ELSE 
        BEGIN
            WHILE CHARINDEX(',', @A2) > 0 
                BEGIN
                    SELECT  @singlePtypeid = CAST(LEFT(@A2, CHARINDEX(',', @A2) - 1) AS INT)
                    INSERT  INTO #TmpP( PTypeID )
                            SELECT  a.PtypeId
                            FROM    dbo.PtypeAttribute a
                            WHERE   a.AttributeID = @singlePtypeid 
                            AND PtypeId NOT IN ( SELECT PTypeID FROM #TmpP )
                    SELECT  @A2 = SUBSTRING(@A2, CHARINDEX(',', @A2) + 1, LEN(@A2))
                END
        END 

    DECLARE @str VARCHAR(10) 
    IF LEFT(@branchid, 5) = '00001'
        OR @branchid = '' 
        BEGIN    
            SET @str = '2,3,4'          
        END    
    ELSE 
        BEGIN    
            SET @str = '6'       
        END  

		IF object_id('tempdb..#P') is not null  
			drop table #P
		IF object_id('tempdb..#b') is not null  
			drop table #b
		IF object_id('tempdb..#e') is not null  
			drop table #e
		IF object_id('tempdb..#br') is not null  
			drop table #br
		SELECT TypeId INTO #P FROM  FN_GetPowerRangePList(@OperatorId, @szPtypeId)
		SELECT Typeid INTO #b FROM  FN_GetPowerRangeBList(@OperatorId, @szBtypeid, '2,3,4,6')
		SELECT Typeid INTO #e FROM  FN_GetPowerRangeEList(@OperatorId, @EtypeID)
		SELECT KtypeId,selfhelp INTO #br FROM  FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid)

		CREATE CLUSTERED INDEX I_tmp_typeid ON #TmpP(PTypeID)
		CREATE CLUSTERED INDEX I_p_typeid ON #P(TypeId)
		CREATE CLUSTERED INDEX I_e_typeid ON #e(TypeId)
		CREATE CLUSTERED INDEX I_b_typeid ON #b(TypeId)
		CREATE CLUSTERED INDEX I_br_typeid ON #br(KtypeId)
		
-----------
	  SELECT    s.Btypeid ,           --销售数量(不包括补货)      
                ds.[qty]			AS [Qty] ,
                ds.[bargaintotal]   AS STotal ,
                ds.[qty]			AS [TQty] ,
                ds.[bargaintotal]	AS TTotal , 
                ds.[qty]			AS SupplyQty ,
                ds.[bargaintotal]	AS SupplyTotal ,
                ds.CostTotal		AS CostTotal ,
                ds.[bargaintotal]	AS SaleMoney ,
                ds.[taxtotal]		AS Taxtotal ,
                ds.[tax_total]		AS Tax_total ,
                ds.[total]			AS total ,
                ds.bargaintotal		AS BargainTotal,
                ifSupply,
                vchtype
      INTO		#temp_data
      FROM      DlyData S ,
                dlydatadetail ds
      WHERE     S.[date] between @szBeginData and @szEndData 
                AND s.dlyorder = ds.dlyorder
                AND s.BillType = 2 
                AND s.redold = 'F'  
                AND s.OpId=CASE WHEN @OpID = 0 THEN s.Opid ELSE @OpID END
                AND s.usedtype = CASE WHEN s.vchtype IN ( 222, 224 ) THEN 1 ELSE s.usedtype END
                AND EXISTS ( SELECT 1 FROM #TmpP a WHERE s.ptypeid = a.ptypeid )
                AND EXISTS ( SELECT 1 FROM   FN_GetPowerRangeVList(@BranchId) FilterV WHERE  s.vchtype = FilterV.vchtype ) 
                AND s.Dtypeid LIKE @Dtypeid + '%'  --以后换成权限方式     
                AND ( EXISTS ( SELECT 1 FROM   #P FilterP WHERE  s.PtypeId = FilterP.TypeId ))
                AND ( EXISTS ( SELECT 1 FROM   #b FilterB WHERE  s.BtypeId = FilterB.TypeId ))
                AND ( EXISTS ( SELECT 1 FROM   #e FilterE WHERE  s.EtypeId = FilterE.TypeId ))
                AND EXISTS ( SELECT 1 FROM   #br FilterK WHERE  s.ktypeId = Filterk.KtypeId AND selfhelp = @OperatorIsJM )
                AND s.BranchId LIKE @BranchId + '%'

	IF object_id('tempdb..#blist') is not null  
			drop table #blist
	SELECT    typeid , usertype into #blist
                          FROM      FN_GetPowerRangeBList(@OperatorId, @szBtypeID, @str)
                          WHERE     ( @branchid = CASE @str WHEN '6' THEN LEFT(branchid, LEN(@branchid)) ELSE @branchid END )
                                    OR ( branchid = CASE @str WHEN '6' THEN LEFT(@branchid, LEN(branchid)) ELSE branchid END )
                                    
	CREATE CLUSTERED INDEX I_blist_typeid ON #blist(TypeId)
-----------
    SELECT  p.[typeid] AS Btypeid ,
            usertype ,
            SUM(qty) AS qty ,
            SUM(Tqty) Tqty ,
            SUM(TTotal) AS TTotal ,
            SUM(qty) - SUM(Tqty) - SUM(Bqty) + SUM(ISNULL(SupplyQty, 0)) AS Sqty ,
            SUM(Tax_total) AS tax_total ,
            SUM(taxtotal) AS taxtotal ,
            SUM(SaleMoney) AS sTotal ,
            SUM(sTotal) AS Total ,
            SUM(Total) - SUM(BargainTotal) AS ConvertTotal ,
            SUM(SaleMoney) - SUM(Tax_total) AS DeductTotal ,
            SUM(SaleMoney) - SUM(CostTotal) AS Profittotal ,
            SUM(ISNULL(BQty, 0)) + SUM(Tqty) AS BSumQty ,
            SUM(ISNULL(BTotal, 0)) + SUM(TTotal) AS BSumTotal ,
            SUM(ISNULL(BQty, 0)) AS BQty ,
            SUM(ISNULL(BTotal, 0)) AS BTotal ,
            SUM(ISNULL(SupplyQty, 0)) AS SupplyQty ,
            SUM(ISNULL(SupplyTotal, 0)) AS SupplyTotal ,
            SUM(CostTotal) AS CostTotal ,
            CAST(CAST(( CASE WHEN SUM(Total) = 0 THEN 0
                             ELSE ( SUM(Total) - SUM(BargainTotal) )
                                  / SUM(Total)
                        END ) * 100 AS NUMERIC(24, 2)) AS VARCHAR(30)) + '%' AS RLrate
    FROM    ( SELECT    p.[typeid] ,
                        usertype ,
                        ISNULL([Qty], 0) AS [Qty] ,
                        ISNULL([SaleMoney], 0) AS [SaleMoney] ,
                        ISNULL(Total, 0) AS Total ,
                        ISNULL([taxtotal], 0) AS Taxtotal ,
                        ISNULL([tax_total], 0) AS Tax_total ,
                        ISNULL(BargainTotal, 0) AS BargainTotal ,
                        ISNULL(Tqty, 0) AS Tqty ,
                        ISNULL(TTotal, 0) AS TTotal ,
                        ISNULL(STotal, 0) AS STotal ,
                        ISNULL(CostTotal, 0) AS CostTotal ,
                        ISNULL(BQty, 0) AS BQty ,
                        ISNULL(BTotal, 0) AS BTotal ,
                        ISNULL(SupplyQty, 0) AS SupplyQty ,
                        ISNULL(SupplyTotal, 0) AS SupplyTotal
              FROM      #blist p
                        LEFT JOIN ( SELECT  Btypeid ,
                                            SUM(ISNULL(-qty, 0)) qty ,
                                            SUM(ISNULL(-STotal, 0)) STotal ,
                                            SUM(ISNULL(tqty, 0)) tqty ,
                                            SUM(ISNULL(TTotal, 0)) TTotal ,
                                            SUM(ISNULL(-salemoney, 0)) salemoney ,
                                            SUM(ISNULL(-taxtotal, 0)) taxtotal ,
                                            SUM(ISNULL(-Tax_total, 0)) Tax_total ,
                                            SUM(ISNULL(-Total, 0)) Total ,
                                            SUM(ISNULL(-BargainTotal, 0)) BargainTotal ,
                                            SUM(ISNULL(-CostTotal, 0)) AS CostTotal ,
                                            SUM(ISNULL(BQty, 0)) AS BQty ,
                                            SUM(ISNULL(BTotal, 0)) AS BTotal ,
                                            SUM(ISNULL(-SupplyQty, 0)) AS SupplyQty ,
                                            SUM(ISNULL(-SupplyTotal, 0)) AS SupplyTotal
                                    FROM    ( SELECT    Btypeid ,           --销售数量(不包括补货)      
                                                        SUM(ISNULL([qty], 0)) AS [Qty] ,
                                                        SUM(ISNULL(STotal, 0)) AS STotal ,
                                                        0 AS [TQty] ,
                                                        0 AS TTotal ,
                                                        0 AS BQty ,
                                                        0 AS BTotal ,
                                                        0 AS SupplyQty ,
                                                        0 AS SupplyTotal ,
                                                        SUM(ISNULL(CostTotal, 0)) AS CostTotal ,
                                                        SUM(ISNULL(SaleMoney, 0)) AS SaleMoney ,
                                                        SUM(ISNULL(Taxtotal, 0)) AS Taxtotal ,
                                                        SUM(ISNULL(Tax_total, 0)) AS Tax_total ,
                                                        SUM(ISNULL([total], 0)) AS total ,
                                                        SUM(ISNULL(bargaintotal, 0)) AS BargainTotal
                                              FROM      #temp_data
                                              WHERE     ifSupply = 0 AND qty < 0
                                              GROUP BY  Btypeid , vchtype
                                              UNION ALL
                                              SELECT    Btypeid , --     补货数量      
                                                        0 AS [Qty] ,
                                                        0 AS STotal ,
                                                        0 AS [TQty] ,
                                                        0 AS TTotal ,
                                                        0 AS BQty ,
                                                        0 AS BTotal ,
                                                        SUM(ISNULL(SupplyQty, 0)) AS SupplyQty ,
                                                        SUM(ISNULL(SupplyTotal, 0)) AS SupplyTotal ,
                                                        SUM(ISNULL(CostTotal, 0)) AS CostTotal ,
                                                        SUM(ISNULL(SaleMoney, 0)) AS SaleMoney ,
                                                        SUM(ISNULL(Taxtotal, 0)) AS Taxtotal ,
                                                        SUM(ISNULL(Tax_total, 0)) AS Tax_total ,
                                                        SUM(ISNULL(total, 0)) AS total ,
                                                        SUM(ISNULL(BargainTotal, 0)) AS BargainTotal
                                              FROM      #temp_data
                                              WHERE     ifSupply = 1 AND qty < 0
                                              GROUP BY  Btypeid , vchtype
                                              UNION ALL
                                              SELECT    Btypeid ,  -- 退货数量      
                                                        0 AS [Qty] ,
                                                        0 AS STOtal ,
                                                        SUM(ISNULL([TQty], 0)) AS [TQty] ,
                                                        SUM(ISNULL(TTotal, 0)) AS TTotal ,
                                                        0 AS BQty ,
                                                        0 AS BTotal ,
                                                        0 AS SupplyQty ,
                                                        0 AS SupplyTotal ,
                                                        SUM(ISNULL(CostTotal, 0)) AS CostTotal ,
                                                        SUM(ISNULL(SaleMoney, 0)) AS SaleMoney ,
                                                        SUM(ISNULL(Taxtotal, 0)) AS Taxtotal ,
                                                        SUM(ISNULL(Tax_total, 0)) AS Tax_total ,
                                                        SUM(ISNULL(total, 0)) AS total ,
                                                        SUM(ISNULL(BargainTotal, 0)) AS BargainTotal
                                              FROM      #temp_data
                                              WHERE     qty > 0
                                              GROUP BY  Btypeid , vchtype          
                                            ) C
                                    GROUP BY Btypeid
                                  ) Salebill ON p.[typeid] = Salebill.Btypeid
	            ) p
	    GROUP BY [typeid] ,
	            usertype
    ORDER BY p.[typeid]  
   
 
    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].[FN_SaleBillDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FN_SaleBillDetail]
GO
/*
  作者:QF
  时间:2011-08-30			
  主要内容:功能增加 发货类型、退货类型

*/


CREATE Proc FN_SaleBillDetail
( 
	@mode	   varchar(50),
	@startdate varchar(10),  
 	@enddate   varchar(10),  
	@ptypeid   varchar(8000),
	@btypeid   varchar(50),
	@etypeid   varchar(50),
	@ktypeid   varchar(2000),
	@branchid  varchar(2000),
	@OperatorId varchar(50),
	@dtypeid    varchar(50)='',
	@SaleTraitname  varchar(1000)='',
	@vchtype    varchar(100)='',
	@pricetype      TINYINT=0,
	@IsStop BIT = 1  ,
        @ifxiaopiao       VARCHAR(2),     --是否包含未过账小票（1：是，0：否）
        @ifdraft          VARCHAR(2),      --是否包含零售单草稿（1：是，0：否）
	@OpID		INT = 0   --0-全部 , 其他为具体类型 
)
AS

if @SaleTraitname='全部' set @SaleTraitname=''  

--总部和加盟商共用一个，当不进行筛选单据的情况下，要把单据范围补齐  
IF LEFT(@branchid,5)='00001'  
BEGIN  
 IF @vchtype is null or @vchtype=''  
     SET @vchtype='100,11,45,24,12,222,224' --总部统计的销售主体单据  
END  
ELSE  
BEGIN  
 IF @vchtype is null or @vchtype=''  
     SET @vchtype='11,12,45,24'   --加盟商统计的销售主体单据  
END 

	IF object_id('tempdb..#P') is not null  
		drop table #P
	IF object_id('tempdb..#b') is not null  
		drop table #b
	IF object_id('tempdb..#e') is not null  
		drop table #e
	IF object_id('tempdb..#br') is not null  
		drop table #br
	SELECT TypeId,[stop] INTO #P FROM  FN_GetPowerRangePList(@OperatorId, @ptypeid)
	SELECT Typeid INTO #b FROM  FN_GetPowerRangeBList(@OperatorId, @btypeid, '2,3,4,6')
	SELECT Typeid INTO #e FROM  FN_GetPowerRangeEList(@OperatorId, @EtypeID)
	SELECT KtypeId,selfhelp INTO #br FROM  FN_GetStockListOfBranch(@OperatorID, @BranchId, @ktypeid)

	CREATE CLUSTERED INDEX I_p_typeid ON #P(TypeId)
	CREATE CLUSTERED INDEX I_e_typeid ON #e(TypeId)
	CREATE CLUSTERED INDEX I_b_typeid ON #b(TypeId)
	CREATE CLUSTERED INDEX I_br_typeid ON #br(KtypeId)
		

if @Mode='S_SPPHB' --商品排行榜明细
BEGIN
	Select a.[vchcode], a.[vchtype],a.ktypeid,a.ptypeid,a.btypeid,  
	sum(ABS((case when isnull(ad.[qty], 0) > 0 then isnull(ad.[qty], 0) else 0 end))) AS InStock,  
	sum(ABS((case when isnull(ad.[qty], 0) < 0 then isnull(ad.[qty], 0) else 0 end))) AS OutStock,  
	-sum(isnull(ad.[tax_total], 0)) as Total, a.[date],SUM(ad.qty) as cccc,a.RedOld,a.RedWord  
	From  Dlydata a 
	INNER JOIN #P p ON  a.ptypeid=p.typeid  	
	INNER JOIN dlydatadetail ad   ON  a.dlyorder =ad.dlyorder  
	
	Where @startdate<=[date]  and @enddate>=[date] 
	and Left(a.ptypeid, Len(@ptypeid+'%')) like  @ptypeid+'%'  
	and a.usedtype=case when vchtype in(222,224) then 1 else a.usedtype end  
		
	and exists(select 1  from #b FilterB  where a.BtypeId = FilterB.TypeId)    
	and exists(select 1  from #e FilterE  where a.EtypeId = FilterE.TypeId)    
	and exists(select 1  from #br FilterK where a.ktypeId = Filterk.KtypeId)       
	and exists(select 1  from FN_GetPowerRangeVList(@BranchId) FilterV where a.vchtype=FilterV.vchtype)             
	
	Group by a.vchcode,vchtype,[date],a.ktypeid,a.ptypeid,a.btypeid,a.RedOld,a.RedWord  
	order by a.vchcode  
END

IF @Mode='S_xzzk' --销售状况表明细
BEGIN
	Select a.[vchcode], a.[vchtype],a.ktypeid,a.ptypeid,a.btypeid,  
	sum(ABS((case when isnull(ad.[qty], 0) > 0 then isnull(ad.[qty], 0) else 0 end))) AS InStock,  
	sum(ABS((case when isnull(ad.[qty], 0) < 0 then isnull(ad.[qty], 0) else 0 end))) AS OutStock,  
	-sum(isnull(ad.[tax_total], 0)) as Total, a.[date],SUM(ad.qty) as cccc,a.RedOld,a.RedWord  
	From  --Dlydata a
	(
		SELECT * FROM Dlydata where price>0 and @pricetype=1 
		Union all 
		SELECT * FROM Dlydata where @pricetype=0
		Union all
		SELECT * FROM Dlydata where price=0 and @pricetype=2
	)a 
	INNER JOIN #P p ON  a.ptypeid=p.typeid  	
	INNER JOIN dlydatadetail ad   ON  a.dlyorder =ad.dlyorder  
	
	Where @startdate<=[date]  and @enddate>=[date] 
	AND p.[stop] IN (CASE stop WHEN 1 THEN @IsStop ELSE 0 END)
	AND a.OpId = (CASE WHEN @OpID=0 THEN a.OpId ELSE @OpID END )
	--and Left(a.ptypeid, Len(@ptypeid+'%')) like  @ptypeid+'%'  
	and a.usedtype=case when vchtype in(222,224) then 1 else a.usedtype end  
	and (
		     CustValue1 like '%'+@SaleTraitName+'%'    
		     or CustValue2 like '%'+@SaleTraitName+'%'  
		     or CustValue3 like '%'+@SaleTraitName+'%'  
		     or CustValue4 like '%'+@SaleTraitName+'%'  
		     or CustValue5 like '%'+@SaleTraitName+'%'  
		     or CustValue6 like '%'+@SaleTraitName+'%'  
	     )  	
	and  dtypeid like @dtypeid+'%' 
	and exists(select 1  from #b FilterB  where a.BtypeId = FilterB.TypeId)    
	and exists(select 1  from #e FilterE  where a.EtypeId = FilterE.TypeId)    
	and exists(select 1  from #br FilterK where a.ktypeId = Filterk.KtypeId)       
	and exists(select 1  from FN_GetPowerRangeVList(@BranchId) FilterV where a.vchtype=FilterV.vchtype)             
	
	Group by a.vchcode,vchtype,[date],a.ktypeid,a.ptypeid,a.btypeid,a.RedOld,a.RedWord  
	order by a.vchcode  
END

IF @Mode='S_spxsfx' --商品销售分析表明细
BEGIN
	Select a.[vchcode], a.[vchtype],a.ktypeid,a.ptypeid,a.btypeid,  
	sum(ABS((case when isnull(ad.[qty], 0) > 0 then isnull(ad.[qty], 0) else 0 end))) AS InStock,  
	sum(ABS((case when isnull(ad.[qty], 0) < 0 then isnull(ad.[qty], 0) else 0 end))) AS OutStock,  
	-sum(isnull(ad.[tax_total], 0)) as Total, a.[date],SUM(ad.qty) as cccc,a.RedOld,a.RedWord  
	From  Dlydata a 
	INNER JOIN #P p ON  a.ptypeid=p.typeid  	
	INNER JOIN dlydatadetail ad   ON  a.dlyorder =ad.dlyorder  
	
	Where @startdate<=[date]  and @enddate>=[date] 
	AND a.OpId = (CASE WHEN @OpID=0 THEN a.OpId ELSE @OpID END )
	and Left(a.ptypeid, Len(@ptypeid+'%')) like  @ptypeid+'%'  
	and a.usedtype=case when vchtype in(222,224) then 1 else a.usedtype end  
	and (
		     CustValue1 like '%'+@SaleTraitName+'%'    
		     or CustValue2 like '%'+@SaleTraitName+'%'  
		     or CustValue3 like '%'+@SaleTraitName+'%'  
		     or CustValue4 like '%'+@SaleTraitName+'%'  
		     or CustValue5 like '%'+@SaleTraitName+'%'  
		     or CustValue6 like '%'+@SaleTraitName+'%'  
	     )  	
	and  dtypeid like @dtypeid+'%' 
	and exists(select 1  from #b FilterB  where a.BtypeId = FilterB.TypeId)    
	and exists(select 1  from #e FilterE  where a.EtypeId = FilterE.TypeId)    
	and exists(select 1  from #br FilterK where a.ktypeId = Filterk.KtypeId)       
	and exists(select 1  from FN_GetPowerRangeVList(@BranchId) FilterV where a.vchtype=FilterV.vchtype)             
	and exists(select GetID FROM FN_GetIdStrListTable(@vchtype) FilterVch WHERE a.vchtype=FilterVch.GetID)  --单据类型
	AND p.Stop IN (CASE @IsStop WHEN 1 THEN p.stop ELSE @IsStop END)--是否包含停用商品
	Group by a.vchcode,vchtype,[date],a.ktypeid,a.ptypeid,a.btypeid,a.RedOld,a.RedWord  
	order by a.vchcode  
END

IF @Mode='S_khxsfx' --客户销售分析表明细
BEGIN
	Select ds.[vchcode], ds.[vchtype],   
	sum(ABS((case when isnull(dsd.[qty], 0) > 0 then isnull(dsd.[qty], 0) else 0 end))) AS InStock,  
	sum(ABS((case when isnull(dsd.[qty], 0) < 0 then isnull(dsd.[qty], 0) else 0 end))) AS OutStock,  
	-sum((isnull((dsd.[tax_total]), 0))) as Total, ds.[date],isnull(d.[number], '''') as [number],   
	ds.redold,isnull(d.[summary], '''') as comment,Ptypeid,ds.btypeid,ds.Ktypeid,ds.RedWord  
	from Dlydata ds   
	left join dlyndx d on ds.vchcode=d.vchcode  
	left join dlydatadetail dsd on ds.dlyorder = dsd.dlyorder  
	where  ds.[date] between @startdate and @enddate
	AND ds.OpId=CASE WHEN @OpID = 0 THEN ds.Opid ELSE @OpID END
	and ds.usedtype=case when ds.vchtype in(222,224) then 1 else ds.usedtype end  
	and  ds.dtypeid like @dtypeid+'%' 
	and exists(select 1  from #P FilterP  where ds.PtypeId = FilterP.TypeId)    
	and exists(select 1  from #b FilterB  where ds.BtypeId = FilterB.TypeId)    
	and exists(select 1  from #e FilterE  where ds.EtypeId = FilterE.TypeId)    
	and exists(select 1  from #br FilterK where ds.ktypeId = Filterk.KtypeId)       
	and exists(select 1  from FN_GetPowerRangeVList(@BranchId) FilterV where ds.vchtype=FilterV.vchtype)             
	group by ds.vchcode,ds.vchtype,ds.[date],d.number,ds.redold,d.summary,Ptypeid,ds.btypeid,ds.Ktypeid,ds.RedWord  
END

IF @mode='S_khyw'--客户业务统计明细
BEGIN	
	Select v.*,atypeid 
	From
	(   
	    select a.vchcode, a.vchtype, a.atypeid, a.date,  
	     b.redold, a.btypeid, b.number, b.summary as comment,  
	     a.total,  
	     case when a.total > 0 then a.total else 0 end as increase,  
	     case when a.total < 0 then -1*a.total else 0 end as reduce,-(a.Total) as ReverseTotal,  
	     a.redword,b.BranchId  
	     from 
	     dlyndx b inner join dlya a  on b.vchcode = a.vchcode 
	     left join btype c  on a.btypeid = c.typeid	      
	    where @startdate<=b.[date] and @enddate>=b.[date]  	   
	    	and a.atypeid ='0000100005' 		       
	    	and b.vchtype in(100,101,11,45,26,24,13,12,222,224,4,36,93,115,66)  	    
	    	and exists(select 1  from #b FilterB  where a.BtypeId = FilterB.TypeId)      --权限  
		and exists(SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorId,@BranchId) FilterVC where a.branchid = FilterVC.branchid)      --权限
	    UNION ALL     
	      
	    select a.vchcode, a.vchtype, a.atypeid, a.date,   
	     b.redold, a.btypeid, b.number, b.summary as comment,  
	     -1*a.total total,  
	     case when a.total < 0 then -1*a.total else 0 end as increase,  
	     case when a.total > 0 then a.total else 0 end as reduce,a.total as ReverseTotal,  
	     a.redword,b.BranchId  
	    from dlyndx b inner join dlya a on b.vchcode = a.vchcode  
	     		  left join btype c on a.btypeid = c.typeid       
	    where @startdate<=b.[date] and @enddate>=b.[date]  
	    	and b.vchtype in(100,101,11,45,26,24,13,12,222,224,4,36,93,115,66)  	    
	    	and a.atypeid='0000200001'  	      
	    	and exists(select 1  from #b FilterB  where a.BtypeId = FilterB.TypeId)      --权限	
		and exists(SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorId,@BranchId) FilterVC where a.branchid = FilterVC.branchid)      --权限
	    UNION ALL  
	    select distinct a.vchcode, a.vchtype, ''as atypeid, a.date,   
	         b.redold, a.btypeid, b.number, b.summary as comment,    
	        0 as total,    
	        0 as increase,    
	        0 as reduce,0 as ReverseTotal,a.redword,b.BranchId    
	        from dlyndx b inner join   
	     	(
			Select distinct btypeid,vchcode,vchtype,[date],redword from dlya   
	      		where vchcode not in (Select vchcode from dlya where atypeid ='0000100005' or atypeid='0000200001')
	     	)a on b.vchcode = a.vchcode           
	        left join btype c on a.btypeid = c.typeid               
	        where @startdate<=b.[date] and @enddate>=b.[date]    
	     	and b.vchtype in(100,101,11,45,26,24,13,12,222,224,4,36,93,115,66)  	        
		and exists(select 1  from #b FilterB  where a.BtypeId = FilterB.TypeId)      --权限   
		and exists(SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorId,@BranchId) FilterVC where b.branchid = FilterVC.branchid)      --权限
	) v 
	left join atype aa  
	on v.atypeid = aa.typeid and v.BranchId = aa.BranchId   
	WHERE v.Increase <> 0 OR Reduce <> 0	--应收增加为0 且 应收减少为0 即不显示  
	order by v.vchcode 
END

IF @mode='lsxstj'--零售销售统计明细
BEGIN

	IF OBJECT_ID('tempdb..#temp_data') IS NOT NULL 
	   DROP TABLE #temp_data 
	CREATE TABLE #temp_data   --创建临时表
	(
        vchcode  int,
        vchtype  int,
		InStock  numeric(24,10),
		OutStock numeric(24,10),
		Total    numeric(24,10),
        [date]   varchar(20),
        [number] varchar(50),
        comment  varchar(500),
        ptypeid  varchar(50),
        btypeid  varchar(50),
        ktypeid  varchar(50),
        redold   char(1),
        RedWord  char(1),
        Draft	 INT
	)
	
        INSERT INTO #temp_data
	Select ds.[vchcode], ds.[vchtype],   
	sum(ABS((case when isnull(dsd.[qty], 0) > 0 then isnull(dsd.[qty], 0) else 0 end))) AS InStock,  
	sum(ABS((case when isnull(dsd.[qty], 0) < 0 then isnull(dsd.[qty], 0) else 0 end))) AS OutStock,  
	-sum((isnull((dsd.[tax_total]), 0))) as Total, 
        ds.[date], 
        isnull(d.[number],'''') as [number],  
	isnull(d.[summary], '''') as comment,Ptypeid,ds.btypeid,ds.Ktypeid,ds.redold,ds.RedWord,d.Draft  
	from Dlydata ds   
	left join Btype b  on ds.Btypeid =b.typeid  
	left join dlyndx d on ds.vchcode=d.vchcode   
	left join ptype p on ds.ptypeid=p.typeid  
	left join dlydatadetail dsd on ds.dlyorder = dsd.dlyorder  
	where  ds.vchtype in(12,13,100,101)   
	and ds.[date] between @startdate and @enddate  			
	and (
		        CustValue1 like '%'+@SaleTraitName+'%'    
		     or CustValue2 like '%'+@SaleTraitName+'%'  
		     or CustValue3 like '%'+@SaleTraitName+'%'  
		     or CustValue4 like '%'+@SaleTraitName+'%'  
		     or CustValue5 like '%'+@SaleTraitName+'%'  
		     or CustValue6 like '%'+@SaleTraitName+'%'  
	     )  		

	AND p.Stop IN (CASE @IsStop WHEN 1 THEN p.stop ELSE @IsStop END)--是否包含停用商品     	
	group by ds.vchcode,ds.vchtype,ds.[date],d.number,d.summary,Ptypeid,ds.btypeid,ds.Ktypeid,ds.redold,ds.RedWord,d.Draft  


	IF  @ifdraft=1  --统计包含零售单草稿
	BEGIN 
	INSERT INTO #temp_data
				Select	    
									b.vchcode,
						b.vchtype, 
				sum(ABS((case when isnull(bd.[qty], 0) < 0 then isnull(bd.[qty], 0) else 0 end))) AS InStock, 
				sum(ABS((case when isnull(bd.[qty], 0) > 0 then isnull(bd.[qty], 0) else 0 end))) AS OutStock, 
				sum((isnull((bd.[tax_total]), 0))) as Total,    
						b.[date],
					   [number]=' ',
						comment=' ',
						b.ptypeid,
						b.btypeid,
						b.ktypeid,
						redold='F',
						RedWord='F',d.Draft
			 FROM    Bakdly b, BakDlyDetail bd LEFT JOIN dlyndx d ON d.Vchcode = bd.Vchcode 
		where  b.vchtype in(12,13,100,101)   
		AND B.DlyOrder = BD.DlyOrder  
		and b.[date] between @startdate and @enddate  			
		and (
					CustValue1 like '%'+@SaleTraitName+'%'    
				 or CustValue2 like '%'+@SaleTraitName+'%'  
				 or CustValue3 like '%'+@SaleTraitName+'%'  
				 or CustValue4 like '%'+@SaleTraitName+'%'  
				 or CustValue5 like '%'+@SaleTraitName+'%'  
				 or CustValue6 like '%'+@SaleTraitName+'%'  
			 )  		
		and exists(select 1  from #P FilterP  where b.PtypeId = FilterP.TypeId)    
		and exists(select 1  from #b FilterB  where b.BtypeId = FilterB.TypeId)
		and exists(select 1  from FN_GetPowerRangeEList(@OperatorId,'') FilterE  where b.EtypeId = FilterE.TypeId)      	
		and exists(select 1  from #br FilterK where b.ktypeId = Filterk.KtypeId) 	
		group by b.vchcode,b.vchtype,b.[date],b.Ptypeid,b.btypeid,b.Ktypeid,d.Draft 
	END

	IF  @ifxiaopiao=1 AND @SaleTraitName = '' --统计包含未过账小票
	BEGIN

	INSERT INTO #temp_data
				SELECT 0 as vchcode,CASE WHEN BtypeID LIKE '00003%' THEN 100 ELSE 12 END AS vchtype,	--未过账小票按机构分为代销零售单和零售单 
				sum(ABS((case when isnull(PSL.[qty], 0) < 0 then isnull(PSL.[qty], 0) else 0 end))) AS InStock, 
				sum(ABS((case when isnull(PSL.[qty], 0) > 0 then isnull(PSL.[qty], 0) else 0 end))) AS OutStock, 
					   PSL.[total] AS Total,    
					   CONVERT(VARCHAR,PSI.SaleDate,23) AS [date],
						[number]=' ',
						comment=' ',
						PSL.ptypeid,
						PSI.btypeid,
						PSI.ktypeid,
						redold='F',
						RedWord='F',psi.Draft  
		FROM    dbo.tpx_SaleList PSL,dbo.tpx_SaleIndex PSI
		WHERE   PSI.[Saledate] between @startdate and @enddate 
			AND PSL.Ptypeid<>''
				AND PSL.ZBKeyId=PSI.keyId           
			and exists(select 1  from #P FilterP  where PSL.PtypeId = FilterP.TypeId)    
		and exists(select 1  from #b FilterB  where PSI.BtypeId = FilterB.TypeId)
		and exists(select 1  from FN_GetPowerRangeEList(@OperatorId,'') FilterE  where PSI.Salesman = FilterE.TypeId)      	
		and exists(select 1  from #br FilterK where PSI.ktypeId = Filterk.KtypeId) 	
			AND PSI.Draft=0 --Draft 结存标志[0-POS小票,1-草稿] 
			group by PSL.[total], PSI.SaleDate,PSL.ptypeid,PSI.btypeid,PSI.ktypeid,psi.Draft
	END

	SELECT vchcode,VchType,InStock,OutStock,Total,[date],[number],comment,ptypeid,btypeid,ktypeid,redold,RedWord,Draft FROM #temp_data
	WHERE 1 = 1
	and exists(select 1  from #P FilterP  where #temp_data.PtypeId = FilterP.TypeId AND (@IsStop = 1 OR Stop = 0))
	and exists(select 1  from #b FilterB  where #temp_data.BtypeId = FilterB.TypeId)
	--and exists(select 1  from FN_GetPowerRangeEList(@OperatorId,'') FilterE  where #temp_data.EtypeId = FilterE.TypeId)      	
	and exists(select 1  from FN_GetStockListOfBranch(@OperatorID,@BranchId,@Ktypeid) FilterK where #temp_data.ktypeId = Filterk.KtypeId)

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



/******************************************20131022********************************************/
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZNewReportSaleBillDetail]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZNewReportSaleBillDetail]
GO

SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO
/*      
销售明细分析
*/      
Create PROC FZNewReportSaleBillDetail
(      
  @dynTable as DynParameterTable readonly
  , @sqlCmd nvarchar(max) out --输出参数, 业务Sql片段
  , @decSql nvarchar(max) out --输出参数，参数声明Sql片段
  , @specSql nvarchar(max) out --输出参数，参数赋值Sql片段    
)       
AS 
BEGIN

DECLARE @SQLCmd1 VARCHAR(MAX)
--配置列,显示列
DECLARE @dlistfield VARCHAR(MAX),@ddistdetailfield VARCHAR(MAX)
--查询字段,查询条件,分组字段,最终排序字段
DECLARE @Fields VARCHAR(MAX),@AssistWheres VARCHAR(MAX),@Group VARCHAR(MAX),@DataOrder VARCHAR(MAX)

SET @SQLCmd1 = N''
set @decSql = N'@dynParamTable as DynParameterTable readonly'
set @specSql = N'@dynParamTable'

SELECT @decSql += nchar(10) + nchar(9) + N', @' + ParaField + N' ' + DataType,
	   @specSql += nchar(10) + nchar(9) + isnull(N', ''' + ParaValue + N'''', ', null')
from @dynTable
WHERE datatype <> ''


SELECT @dlistfield = 'number,vchtypeid,ptypeid,btypeid,etypeid,opername,vchcode,draft,inputno,redold,redword'	--查看原始单据参数A.Vchcode,A.Draft,A.InputNo,是否红冲(redold),是否红冲产生新单(redword)
SELECT @ddistdetailfield = LOWER(ParaValue) FROM @dynTable WHERE ParaField = 'ddistdetailfield'		

---->@ddistdetailfield --TO--> @dlistfield
IF(CHARINDEX(',price,',','+@ddistdetailfield+',') > 0)				--单价
BEGIN
	DECLARE @temp VARCHAR(MAX)
	SET @dlistfield = @dlistfield+',price'
	SET @temp = REPLACE(','+@ddistdetailfield+',',',price,',',')
	IF(@temp = ',')
		SET @ddistdetailfield = ''
	ELSE
		SET @ddistdetailfield = SUBSTRING(@temp,2,LEN(@temp)-2)
END
IF(CHARINDEX(',taxprice,',','+@ddistdetailfield+',') > 0)			--含税单价
BEGIN
	SET @dlistfield = @dlistfield+',taxprice'
	SET @temp = REPLACE(','+@ddistdetailfield+',',',taxprice,',',')
	IF(@temp = ',')
		SET @ddistdetailfield = ''
	ELSE
		SET @ddistdetailfield = SUBSTRING(@temp,2,LEN(@temp)-2)
END
IF(CHARINDEX(',refprice,',','+@ddistdetailfield+',') > 0)			--参考单价
BEGIN
	SET @dlistfield = @dlistfield+',refprice'
	SET @temp = REPLACE(','+@ddistdetailfield+',',',refprice,',',')
	IF(@temp = ',')
		SET @ddistdetailfield = ''
	ELSE
		SET @ddistdetailfield = SUBSTRING(@temp,2,LEN(@temp)-2)
	
END
IF(CHARINDEX(',discount,',','+@ddistdetailfield+',') > 0)			--折扣
BEGIN
	SET @dlistfield = @dlistfield+',discount'
	SET @temp = REPLACE(','+@ddistdetailfield+',',',discount,',',')
	IF(@temp = ',')
		SET @ddistdetailfield = ''
	ELSE
		SET @ddistdetailfield = SUBSTRING(@temp,2,LEN(@temp)-2)
END
IF(CHARINDEX(',discountprice,',','+@ddistdetailfield+',') > 0)		--折后单价
BEGIN
	SET @dlistfield = @dlistfield+',discountprice'
	SET @temp = REPLACE(','+@ddistdetailfield+',',',discountprice,',',')
	IF(@temp = ',')
		SET @ddistdetailfield = ''
	ELSE
		SET @ddistdetailfield = SUBSTRING(@temp,2,LEN(@temp)-2)
END
IF(CHARINDEX(',vipdiscount,',','+@ddistdetailfield+',') > 0)		--VIP折扣
BEGIN
	SET @dlistfield = @dlistfield+',vipdiscount'
	SET @temp = REPLACE(','+@ddistdetailfield+',',',vipdiscount,',',')
	IF(@temp = ',')
		SET @ddistdetailfield = ''
	ELSE
		SET @ddistdetailfield = SUBSTRING(@temp,2,LEN(@temp)-2)
END
IF(CHARINDEX(',tax,',','+@ddistdetailfield+',') > 0)				--税率
BEGIN
	SET @dlistfield = @dlistfield+',tax'
	SET @temp = REPLACE(','+@ddistdetailfield+',',',tax,',',')
	IF(@temp = ',')
		SET @ddistdetailfield = ''
	ELSE
		SET @ddistdetailfield = SUBSTRING(@temp,2,LEN(@temp)-2)
END

--最终排序字段
SET @DataOrder = @dlistfield

--设置查询条件
SET @AssistWheres = ''
IF 0 = 0
BEGIN
	IF(EXISTS(SELECT 1 FROM @dynTable WHERE ParaField = 'assist1' AND ParaValue IS NOT NULL))
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (@assist1 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = B.PtypeId AND pa.AttributeID = @assist1))'
	END
	IF(EXISTS(SELECT 1 FROM @dynTable WHERE ParaField = 'assist2' AND ParaValue IS NOT NULL))
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (@assist2 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = B.PtypeId AND pa.AttributeID = @assist2))'
	END
	IF(EXISTS(SELECT 1 FROM @dynTable WHERE ParaField = 'assist3' AND ParaValue IS NOT NULL))
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (@assist3 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = B.PtypeId AND pa.AttributeID = @assist3))'
	END
	IF(EXISTS(SELECT 1 FROM @dynTable WHERE ParaField = 'assist4' AND ParaValue IS NOT NULL))
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (@assist4 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = B.PtypeId AND pa.AttributeID = @assist4))'
	END
	IF(EXISTS(SELECT 1 FROM @dynTable WHERE ParaField = 'assist5' AND ParaValue IS NOT NULL))
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (@assist5 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = B.PtypeId AND pa.AttributeID = @assist5))'
	END
	IF(EXISTS(SELECT 1 FROM @dynTable WHERE ParaField = 'assist6' AND ParaValue IS NOT NULL))
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (@assist6 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = B.PtypeId AND pa.AttributeID = @assist6))'
	END
	IF(EXISTS(SELECT 1 FROM @dynTable WHERE ParaField = 'assist7' AND ParaValue IS NOT NULL))
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (@assist7 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = B.PtypeId AND pa.AttributeID = @assist7))'
	END
	IF(EXISTS(SELECT 1 FROM @dynTable WHERE ParaField = 'assist8' AND ParaValue IS NOT NULL))
	BEGIN
		SET @AssistWheres = @AssistWheres+'
	AND (@assist8 IS NULL OR EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa WHERE pa.PtypeId = B.PtypeId AND pa.AttributeID = @assist8))'
	END
END


IF 1 = 1		--配置列
BEGIN
	SET @Fields = ','+@dlistfield+','
	--单据编号
	SET @Fields = REPLACE(@Fields,',number,',	',a.number,')
	--单据类型
	SET @Fields = REPLACE(@Fields,',vchtypeid,',',a.vchtypeid,')
	--发/退货类型
	SET @Fields = REPLACE(@Fields,',opername,',	',e.opername,')
	--商品
	SET @Fields = REPLACE(@Fields,',ptypeid,',	',b.ptypeid,')
	--客户
	SET @Fields = REPLACE(@Fields,',btypeid,',	',a.btypeid,')
	--经手人
	SET @Fields = REPLACE(@Fields,',etypeid,',	',a.etypeid,')
	
	--单价
	SET @Fields = REPLACE(@Fields,',price,',	',b.price,')
	--含税单价
	SET @Fields = REPLACE(@Fields,',taxprice,',	',b.taxprice,')
	--参考单价
	SET @Fields = REPLACE(@Fields,',refprice,',	',d.refprice,')
	--折扣
	SET @Fields = REPLACE(@Fields,',discount,',	',b.discount,')
	--折后单价
	SET @Fields = REPLACE(@Fields,',discountprice,',	',b.discountprice,')
	--VIP折扣
	SET @Fields = REPLACE(@Fields,',vipdiscount,',	',b.vipdiscount,')
	--税率
	SET @Fields = REPLACE(@Fields,',tax,',	',b.tax,')
	
	--单据编号
	SET @Fields = REPLACE(@Fields,',vchcode,',	',a.vchcode,')
	--是否草稿
	SET @Fields = REPLACE(@Fields,',draft,',	',a.draft,')
	--录单人
	SET @Fields = REPLACE(@Fields,',inputno,',	',a.inputno,')
	--录单人
	SET @Fields = REPLACE(@Fields,',inputno,',	',a.inputno,')
	--是否红冲
	SET @Fields = REPLACE(@Fields,',redold,',	',a.redold,')
	--是否红冲产生新单
	SET @Fields = REPLACE(@Fields,',redword,',	',a.redword,')
	
	SET @dlistfield = SUBSTRING(@Fields,2,LEN(@Fields)-2)
END

IF 2 = 2		--显示列
BEGIN 
	SET @Fields = ','+@ddistdetailfield+','
	
	--数量
	SET @Fields = REPLACE(@Fields,',qty,',		',
	-sum(b.qty) qty,')
	--金额
	SET @Fields = REPLACE(@Fields,',total,',		',
	-sum(b.total) total,')
	--参考金额
	SET @Fields = REPLACE(@Fields,',reftotal,',		',
	sum(round(isnull(d.refprice,0)*-b.qty,@dig_total)) reftotal,')
	--折后金额
	SET @Fields = REPLACE(@Fields,',discounttotal,',		',
	-sum(b.discounttotal) discounttotal,')
	--折让
	SET @Fields = REPLACE(@Fields,',convert1,',		',
	case when a.vchtypeid = 11 then -sum(b.[convert])				--销售出库单
		 when a.vchtypeid = 45 then -sum(b.[convert])				--销售退货单
		 when a.vchtypeid = 24 and b.Usedtype = 1 then -sum(b.[convert])	--销售换货单
		 when a.vchtypeid = 24 and b.Usedtype = 2 then sum(b.[convert])
		 else 0 end convert1,')
	--成交金额
	SET @Fields = REPLACE(@Fields,',bargaintotal,',		',
	-sum(b.bargaintotal) bargaintotal,')
	--税额
	SET @Fields = REPLACE(@Fields,',taxtotal,',		',
	-sum(b.taxtotal) taxtotal,')
	--含税金额
	SET @Fields = REPLACE(@Fields,',salemoney,',		',
	-sum(b.salemoney) salemoney,')
	
	SET @ddistdetailfield = SUBSTRING(@Fields,2,LEN(@Fields)-2)
END

--设置查询字段
IF @ddistdetailfield IS NULL OR @ddistdetailfield = ''
BEGIN
	SET @Fields = @dlistfield
	SET @Fields = REPLACE(@Fields,',d.refprice',	',isnull(d.refprice,0) as refprice')
END	
ELSE
BEGIN
	SET @Fields = @dlistfield+','+@ddistdetailfield
	SET @Fields = REPLACE(@Fields,',d.refprice',	',isnull(d.refprice,0) as refprice')
END	
	
--设置分组字段
SET @Group = 'GROUP BY b.Usedtype,'+@dlistfield

SET @SQLCmd1 ='
DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 

IF object_id(''''tempdb..#vchtypesplit'''') is not null
	drop table #vchtypesplit
SELECT * INTO #vchtypesplit
FROM dbo.Fn_split(@vchtypeid,'''','''')


--业务类型列表
DECLARE @opid NVARCHAR(500)
SET @opid = ISNULL(@opid1,'''''''')+'''',''''+ISNULL(@opid3,'''''''')
IF object_id(''''tempdb..#opidsplit'''') is not null
	drop table #opidsplit
SELECT * INTO #opidsplit
FROM dbo.Fn_split(@opid,'''','''') WHERE a <> ''''''''

--仓库多级权限
IF(OBJECT_ID(''''tempdb..#KListTemp'''') IS NOT NULL)
	DROP TABLE #KListTemp
SELECT KtypeId AS TypeID INTO #KListTemp FROM dbo.FN_GetStockListOfBranch(@oprid,'''''''','''''''')

--商品多级权限
IF(OBJECT_ID(''''tempdb..#PListTemp'''') IS NOT NULL)
	DROP TABLE #PListTemp
SELECT TypeID,[stop] INTO #PListTemp FROM dbo.FN_GetPowerRangePList(@oprid,'''''''')

--供应商多级权限
IF(OBJECT_ID(''''tempdb..#BListTemp'''') IS NOT NULL)
	DROP TABLE #BListTemp
SELECT TypeID INTO #BListTemp FROM dbo.FN_GetPowerRangeBList(@oprid, '''''''', ''''2,6'''')	--2 表示 客户|6 表示 加盟客户

--经手人多级权限
IF(OBJECT_ID(''''tempdb..#EListTemp'''') IS NOT NULL)
	DROP TABLE #EListTemp
SELECT TypeID INTO #EListTemp FROM dbo.FN_GetPowerRangeEList(@oprid, '''''''') 

IF object_id(''''tempdb..#tmpsort'''') is not null
                drop table #tmpsort
SELECT tmpsort.* INTO #tmpsort
FROM ( 
-------------------------------------------------------------------------
	SELECT __Fields__
	FROM 
	( 
	 SELECT number,CAST(vchtype AS INT) AS vchtypeid,btypeid,etypeid,vchcode,draft,inputno,redold,redword,[date]  FROM DlyNDX
	)  A
	INNER JOIN DLYDATA B ON A.VCHCODE = B.VCHCODE
	LEFT JOIN (
				SELECT Ptypeid,PriceTypeid,Price RefPrice FROM PtypePrice
			  ) D ON B.Ptypeid  = D.Ptypeid AND D.PriceTypeid = @salepriceid
	INNER JOIN OperationInfo E ON B.OpID = E.OpID
	WHERE 1 = 1 
	__AssistWheres__
	AND A.Draft IN (2,4)
	AND ((@isred = ''''0'''') OR (@isred = ''''T'''' AND A.Redold = ''''T'''') OR (@isred = ''''F'''' AND A.Redold = ''''F''''))
	AND EXISTS (SELECT #KListTemp.TypeID FROM #KListTemp WHERE #KListTemp.TypeID = B.KtypeId)	
	AND EXISTS (SELECT #PListTemp.TypeID FROM #PListTemp WHERE #PListTemp.TypeID = B.Ptypeid AND #PListTemp.[stop] IN (CASE stop WHEN 1 THEN @containsstop ELSE 0 END))
	AND EXISTS (SELECT #BListTemp.TypeID FROM #BListTemp WHERE #BListTemp.TypeID = A.Btypeid)
	AND EXISTS (SELECT #EListTemp.TypeID FROM #EListTemp WHERE #EListTemp.TypeID = A.Etypeid)
	AND (B.BranchId LIKE @branchid OR @branchid IS NULL)
	AND (B.KTypeID LIKE @ktypeid  OR @ktypeid IS NULL)
	AND (B.BTypeID LIKE @btypeid OR @btypeid IS NULL)
	AND (B.ETypeID LIKE @etypeid OR @etypeid IS NULL)
	AND EXISTS (SELECT 1 FROM #vchtypesplit WHERE #vchtypesplit.a = A.vchtypeid)
	AND EXISTS (SELECT 1 FROM #opidsplit WHERE #opidsplit.a = B.Opid)
	AND A.[date] BETWEEN @billdate_s + '''' 00:00:00.000'''' AND @billdate_e + '''' 23:59:59.999'''' 
	AND (@definename IS NULL OR (custvalue1 LIKE @definename OR custvalue2 LIKE @definename OR custvalue3 LIKE @definename OR custvalue4 LIKE @definename OR custvalue5 LIKE @definename OR custvalue6 LIKE @definename))
	AND (B.Ptypeid LIKE @ptypeid OR @ptypeid IS NULL)
	__Group__
-------------------------------------------------------------------------
) tmpsort; 

/*最终结果表*/
with Data AS (
SELECT * FROM #tmpsort
),'

SET @SQLCmd1 = REPLACE(@SQLCmd1,'__Fields__',			@Fields)
SET @SQLCmd1 = REPLACE(@SQLCmd1,'__AssistWheres__',		@AssistWheres)
SET @SQLCmd1 = REPLACE(@SQLCmd1,'__Group__',			@Group)

SET @DataOrder = 'DATA.' + REPLACE(@DataOrder,',',		',DATA.')

-- 排序信息
declare @sortInfo varchar(255) = isnull((select ParaValue from @dynTable where ParaField = '__SortInfo__') + ',', '')
-- 排序联接信息
declare @sortJoinInfo varchar(555) = isnull((select replace(ParaValue, '__LeftTable__', 'Data') from @dynTable where ParaField = '__SortJoinInfo__'), '')
	
set @sqlCmd = cast(
(
	@SQLCmd1
	+ '
	__ReportData__ AS (
	select dense_rank() over (order by ' + @sortInfo + @DataOrder + ' desc) __RowNo__,DATA.*
	from Data ' + @sortJoinInfo + ')'
) as nvarchar(max))

END
GO






/******************************************20131105********************************************/
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO
-- 将字符串如：‘20，23，26’转换成表记录如：
--                                        20
--                                        23
--                                        26
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetVchtypeOrVchcode]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetVchtypeOrVchcode]
GO



CREATE FUNCTION [GetVchtypeOrVchcode] (
@List varchar(max),
@type BIT -- 0 取单据编号 1：取单据类型
)  
RETURNS @table table(
 VchtypeOrVchcode NUMERIC(10,0)
) AS  
BEGIN 

	if @List is null set @List=''
        declare @VchtypeOrVchcode   NUMERIC(10,0)
        declare @CharIndex   int
        declare @MaxCount    int
        select @VchtypeOrVchcode = 0
        select @MaxCount = 0
        if @type=1 and @list=''
          
           Insert @table select vchtype from vchtype where typeid<>0 and sonnum=0
        else
        Begin
	        while(@List <> '' and @MaxCount <= 100000 and CAST(@VchtypeOrVchcode as VARCHAR(max)) <> @List)
	        begin
	          select @CharIndex = CHARINDEX( ',', @List,1)
	          if @CharIndex > 0 
	          begin
	              select @VchtypeOrVchcode = CAST(substring(@List,1,@CharIndex - 1) as  NUMERIC(10,0))
	              select @List = substring(@List,@CharIndex + 1,len(@List))
	          end
	          else if @List <> ''
	          begin
	              select @VchtypeOrVchcode = CAST(substring(@List,1,len(@List) ) as  NUMERIC(10,0))
	               select @List = CAST(@VchtypeOrVchcode as VARCHAR(max))
	          end
	          if @VchtypeOrVchcode <> 0
		          Insert @table 
		                    select @VchtypeOrVchcode
		          select @MaxCount = @MaxCount + 1
	        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 1
           FROM   dbo.sysobjects
           WHERE  id = object_id(N'[dbo].[FZSearchLoadVchdetail]')
                  AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
  DROP PROCEDURE [dbo].[FZSearchLoadVchdetail]

GO

--  ******************************************************************************************
--  ||                                                                                        
--  ||   SearchLoadVchdetail                                     
--  ||==========================================================================================
CREATE PROCEDURE FZSearchLoadVchdetail (
  @LoadVchType  INT,
  @OrderVchList VARCHAR(max),
  @PtypeId      VARCHAR(50),
  @ColorId      INT
)
AS
    DECLARE @szSql VARCHAR(max)

    SET @OrderVchList=Rtrim(@OrderVchList)

    IF @LoadVchType IN (7, 8, 221, 223,
                        211, 214) -- 调订单
      BEGIN
          IF EXISTS(SELECT 1
                    FROM   sysdata
                    WHERE  subname = 'ProcTypeName'
                           AND subvalue = 'FZBS')
            BEGIN
                SELECT p.TypeID,
                       p.UserCode,
                       p.FullName,
                       p.costmode,
                       o.Vchtype,
                       d.ifsupply,
                       o.btypeid AS btypeid,
                       o.number AS number,
                       o.btypeid AS Cusid,
                       o.BranchId AS rebcid, 
                       CASE
                         WHEN EXISTS(SELECT 1
                                     FROM   BtypeSupply bs
                                     WHERE  bs.btypeid = CASE
                                                           WHEN @LoadVchType = 211 THEN d.KtypeId
                                                           ELSE d.Btypeid
                                                         END
                                            AND bs.ptypeid = d.ptypeid
                                            AND bs.ColorId = d.ColorId) THEN 1
                         ELSE 0
                       END                           AS ReStock,
                       d.kTypeID,
                       d.btypeid,
                       d.Qty,
                       d.discount,
                       d.costprice,
                       d.price,
                       d.Tax_Total,
                       d.tax,
                       d.Vchcode,
                       d.dlyorder,
                       p.retailprice,
                       k.fullname                    AS kfullname,
                       b.fullname                    AS bfullname,
                       c.Name                        AS ColorName,
                       d.toqty,
                       --d.qty-d.toqty as DelayQty,
                       (SELECT sum(f.qty - f.toqty)
                        FROM   bakdlyorderdetail f
                        WHERE  f.dlyorder = d.dlyorder
                               AND f.qty >= f.toqty) AS DelayQty,
                       o.todate,
                       d.CustValue1,
                       d.CustValue2,
                       d.CustValue3,
                       d.CustValue4,
                       d.CustValue5,
                       d.CustValue6
                FROM   ptype p
                       INNER JOIN BakDlyOrder d ON p.typeId = d.PtypeId
                       INNER JOIN GetVchtypeOrVchcode(@OrderVchList, 0) V ON d.Vchcode = V.VchtypeOrVchcode
                       INNER JOIN DlyndxOrder o ON d.Vchcode = o.Vchcode
                       LEFT JOIN btype b ON b.typeid = d.btypeid
                       LEFT JOIN stock k ON d.ktypeid = k.typeid
                       LEFT JOIN color c ON d.colorid = c.colorid
                WHERE  d.colorid = CASE
                                     WHEN @ColorId = 0 THEN d.colorid
                                     ELSE @ColorId
                                   END
                       AND p.typeId LIKE CASE @PtypeId
                                           WHEN '' THEN p.typeId
                                           ELSE @PtypeId
                                         END + '%'
                --           and d.toqty<d.qty
                ORDER  BY d.DlyOrder
            END
          ELSE
            BEGIN
                SELECT p.TypeID,
                       p.UserCode,
                       p.FullName,
                       p.costmode,
                       o.Vchtype,
                       d.ifsupply,
                       CASE
                         WHEN EXISTS(SELECT 1
                                     FROM   BtypeSupply bs
                                     WHERE  bs.btypeid = CASE
                                                           WHEN @LoadVchType = 211 THEN d.KtypeId
                                                           ELSE d.Btypeid
                                                         END
                                            AND bs.ptypeid = d.ptypeid
                                            AND bs.ColorId = d.ColorId) THEN 1
                         ELSE 0
                       END             AS ReStock,
                       d.kTypeID,
                       d.btypeid,
                       d.Qty,
                       d.discount,
                       d.costprice,
                       d.price,
                       d.Tax_Total,
                       d.tax,
                       d.Vchcode,
                       d.dlyorder,
                       p.retailprice,
                       k.fullname      AS kfullname,
                       b.fullname      AS bfullname,
                       c.Name          AS ColorName,
                       d.toqty,
                       d.qty - d.toqty AS DelayQty,
                       o.todate,
                       d.CustValue1,
                       d.CustValue2,
                       d.CustValue3,
                       d.CustValue4,
                       d.CustValue5,
                       d.CustValue6,
                       d.isover
                FROM   ptype p
                       INNER JOIN BakDlyOrder d ON p.typeId = d.PtypeId
                       INNER JOIN GetVchtypeOrVchcode(@OrderVchList, 0) V ON d.Vchcode = V.VchtypeOrVchcode
                       INNER JOIN DlyndxOrder o ON d.Vchcode = o.Vchcode
                       LEFT JOIN btype b ON b.typeid = d.btypeid
                       LEFT JOIN stock k ON d.ktypeid = k.typeid
                       LEFT JOIN color c ON d.colorid = c.colorid
                WHERE  d.colorid = CASE
                                     WHEN @ColorId = 0 THEN d.colorid
                                     ELSE @ColorId
                                   END
                       AND p.typeId LIKE CASE @PtypeId
                                           WHEN '' THEN p.typeId
                                           ELSE @PtypeId
                                         END + '%'
                --           and d.toqty<d.qty
                ORDER  BY d.DlyOrder
            END
      END
    ELSE
      BEGIN
          SELECT p.TypeID,
                 p.UserCode,
                 p.FullName,
                 p.costmode,
                 o.Vchtype,
                 d.ifsupply,
                 0          AS ReStock,
                 d.kTypeID,
                 d.btypeid,
                 d.Qty,
                 d.discount,
                 d.costprice,
                 d.price,
                 d.Tax_Total,
                 d.tax,
                 d.Vchcode,
                 d.dlyorder,
                 k.fullname AS kfullname,
                 b.fullname AS bfullname,
                 c.Name     AS ColorName,
                 0          AS toqty,
                 0          AS DelayQty,
                 o.flag     AS CarryFlag,
                 d.CustValue1,
                 d.CustValue2,
                 d.CustValue3,
                 d.CustValue4,
                 d.CustValue5,
                 d.CustValue6
          FROM   ptype p
                 INNER JOIN dlydata d ON p.typeId = d.PtypeId
                 INNER JOIN GetVchtypeOrVchcode(@OrderVchList, 0) V ON d.Vchcode = CAST(V.VchtypeOrVchcode AS INT)
                 INNER JOIN dlyndx o ON d.Vchcode = o.Vchcode
                 LEFT JOIN btype b ON b.typeid = d.btypeid
                 INNER JOIN stock k ON k.typeid = d.ktypeid
                 LEFT JOIN color c ON d.colorid = c.colorid
          WHERE  p.typeId LIKE CASE @PtypeId
                                 WHEN '' THEN p.typeId
                                 ELSE @PtypeId
                               END + '%'
                 AND d.colorid = CASE
                                   WHEN CONVERT(VARCHAR(10), @ColorId) = 0 THEN d.colorid
                                   ELSE CONVERT(VARCHAR(10), @ColorId)
                                 END
                 AND d.usedtype = 1
                 AND o.Vchtype = CONVERT(NUMERIC(4, 0), @LoadVchType)
          ORDER  BY d.DlyOrder
      END

GO

SET QUOTED_IDENTIFIER OFF

GO

SET ANSI_NULLS ON

GO 





/******************************************20131120********************************************/
--调配单       "00009";  收发货机构
--调拨单       "00008"   收发货机构
--补货申请单   "00004"   收货机构
--退货申请单   "00005"   发货机构
IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZPosCountQuery]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZPosCountQuery]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
    
    
CREATE PROCEDURE FZPosCountQuery
    (
      @SaleDateBegin VARCHAR(10) ,
      @SaleDateEnd VARCHAR(10) ,
      @BranchId VARCHAR(50) ,
      @PosName VARCHAR(30) ,
      @OperatorId VARCHAR(50) = '00000' ,
      @VtypeId VARCHAR(50)
    )
AS 

--构造以逗号分隔开的营业员临时表 e1,e2,e3

select d.keyid ,d.posvchcode,d.SaleTime,d.BillCode,d.Salesman,d.Cashier,
	d.KtypeId,d.ktypeid2,d.VipCardID,d.PosID,d.CheckOutDate,d.Comment INTO #temp_test
from 
	tpx_SaleIndex d 
where ( d.Draft = 0  OR d.DraftVchcode < 0)
	AND d.SaleDate <= @SaleDateEnd
	AND d.SaleDate >= @SaleDateBegin
	AND ISNULL(d.JtypeId, '') LIKE @BranchId + '%'
	AND d.VtypeId = @VtypeId
	AND ( EXISTS ( SELECT   1
				   FROM     FN_GetStockListOfBranch(@OperatorId, '',
													'')
				   WHERE    d.KtypeID = KtypeId )
		  OR d.KtypeID = ''
		)

SELECT DISTINCT   b.ZBKeyId , ee.FullName INTO #ename
FROM      #temp_test s
		INNER JOIN tpx_salelist b ON s.keyId=b.ZBKeyId
        INNER JOIN tpx_SaleManList sml ON sml.CBKeyId = b.keyid
        INNER JOIN dbo.Employee ee ON ee.TypeId = sml.ETypeId
												

SELECT  x.KeyId ,
		Salesman = STUFF(( SELECT   ',' + s.FullName
                           FROM  #ename s
                           WHERE    s.ZBKeyId = x.KeyId
                         FOR
                           XML PATH('')
                         ), 1, 1, '')
INTO    #T
FROM #temp_test X
                                                            
    SELECT  a.KeyId AS KeyId ,
            a.posvchcode ,
            CASE WHEN @VtypeId IN ( '00004', '00009' ) THEN s1.BranchID
                 WHEN @VtypeId = '00008' THEN s2.BranchID
                 ELSE ''
            END BCTypeIds ,    --  收货机构
            CASE WHEN @VtypeId IN ( '00005', '00001' ) THEN s1.BranchID
                 WHEN @VtypeId IN ( '00008', '00009' ) THEN s2.BranchID
                 ELSE ''
            END BCTypeId ,    --  发货机构  
            b.UserCode AS UserCode ,
            b.FullName AS FullName ,
            a.SaleTime AS SaleDateTime ,
            a.BillCode AS BillCode ,
            CASE WHEN @VtypeId IN ( '00004', '00009', '00008' ) THEN a.KtypeId
                 ELSE ''
            END KtypeIds ,    --  收货仓库
            CASE WHEN @VtypeId IN ( '00005', '00001' ) THEN a.KtypeId
                 WHEN @VtypeId IN ( '00008', '00009' ) THEN a.ktypeid2
                 ELSE ''
            END KtypeId ,    --  发货仓库
            c.FullName AS Cashier ,
            c.TypeId AS CashierId ,
            ISNULL(d.FullName, c.FullName) AS hdman ,
            e.Salesman AS Salesman ,
            --handman = ( SELECT TOP 1
            --                    sml.etypeid AS ETypeId
            --            FROM    dbo.tpx_Salelist sl
            --                    LEFT  JOIN tpx_SaleManList sml ON sl.keyid = sml.CBKeyId
            --            WHERE   sl.ZBKeyId = a.keyId
            --          ) ,
            'FALSE' AS virtualflag ,
            a.VipCardID AS VipCardID ,
            a.PosID AS POSID ,
            --CONVERT(VARCHAR(10), a.CheckOutDate, 120) AS CheckOutDate ,
            --a.BtypeID AS BtypeID ,
            a.CheckOutDate AS CheckOutDate,
            a.Comment AS Comment
    FROM    #temp_test a
            LEFT JOIN tpx_PosInfo b ON a.PosID = b.PosID
            LEFT JOIN Employee c ON c.TypeId = a.Cashier
            LEFT JOIN dbo.Employee d ON d.TypeId = a.Salesman
            LEFT JOIN dbo.Stock s1 ON a.ktypeid = s1.TypeID
            LEFT JOIN dbo.Stock s2 ON a.ktypeid2 = s2.TypeID
            LEFT JOIN #T e ON a.keyId = e.KeyId
    WHERE  ISNULL(b.FullName, '') LIKE '%' + @PosName + '%'
    ORDER BY a.posvchcode , a.BillCode ,a.SaleTime   
            
    IF OBJECT_ID('tempdb..#T') IS NOT NULL  DROP TABLE #T
    IF OBJECT_ID('tempdb..#temp_test') IS NOT NULL  DROP TABLE #temp_test
    IF OBJECT_ID('tempdb..#ename') IS NOT NULL  DROP TABLE #ename
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZBS_PosToDraftBill]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZBS_PosToDraftBill]
GO
--  ********************************************************************************************
--  ||   Create ：老罗  2012-10-19  
--  ||                                                                                   
--  ||   过程名称： FZBS_PosToDraftBill                                   
--  ||   过程功能： 零售小票结转成总部相关单据草稿
--  ||
--  ||==========================================================================================
-- return -1 结存失败，单据插入失败！
-- return -2 结存失败，你选择的单据已经被其他人结存！
CREATE PROCEDURE FZBS_PosToDraftBill
    (
      @ABranchid VARCHAR(50) ,  	--机构ID
      @BillCode VARCHAR(8000) = '' , 	--单据编号
      @ConditionStr VARCHAR(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开
    )
AS 
    DECLARE @Btypeid VARCHAR(50)	--客户
    DECLARE @PosVchcode INT  
    DECLARE @Branchid VARCHAR(50)
    DECLARE @Branchid2 VARCHAR(50)    
    DECLARE @BranchType INT
    DECLARE @KtypeId VARCHAR(50)
    DECLARE @KtypeId2 VARCHAR(50)
    DECLARE @HandleManID VARCHAR(50)
    DECLARE @Etypeid VARCHAR(50)
    DECLARE @VchType INT
    DECLARE @VipCardID VARCHAR(50)
    DECLARE @PosUserCode VARCHAR(50)
    DECLARE @Dtypeid VARCHAR(50) --部门ID
    DECLARE @VchCode VARCHAR(50)
    DECLARE @DetailId INT
    DECLARE @InputName VARCHAR(50)
    DECLARE @site INT= 0
    DECLARE @tmpHandleManID VARCHAR(50)
    DECLARE @tmpetypeid VARCHAR(50)
    DECLARE @tmpType VARCHAR(1)
    DECLARE @tmpVipCardID VARCHAR(50)
    DECLARE @tmpCodeStr VARCHAR(8000)
    DECLARE @Period INT	
    
    DECLARE @CashSum NUMERIC(24, 10)
    DECLARE @BakMoneySum NUMERIC(24, 10)
    DECLARE @ReplaceCashSum NUMERIC(24, 10)
    DECLARE @CreditSum NUMERIC(24, 10)
    DECLARE @VipCardPay NUMERIC(24, 10)
    DECLARE @RetailChange NUMERIC(24, 10)
    DECLARE @RetailSum NUMERIC(24, 10)
    DECLARE @PromRtnReplaceCashSum NUMERIC(24, 10)
    DECLARE @SubValue VARCHAR(10) 
    DECLARE @BillDate VARCHAR(10)
    DECLARE @Keyid VARCHAR(50)   
    DECLARE @Tax NUMERIC(24, 10) 
    DECLARE @Number NVARCHAR(50) 
    DECLARE @Summary VARCHAR(200)= ''
    DECLARE @Comment VARCHAR(200)= ''
    DECLARE @CheckAndAccept BIT= 1
    

    SET @PosVchcode = 0
    	--单据类型
	--00000	所有单据   select * from vchtype
	--00001	零售单
	--00002	订金付入
	--00003	维修单
	--00004	补货申请单  --加盟店配货订单  发货类型为“补货  221
	--00005	退货申请单  --加盟商退货申请单，退货类型为“正常退货”
	--00006	盘点指令单
	--00007	盘点单
	--00008	调拨单      --同价调拨单
	--00009	调配单      --同价配货单，业务类型“调配”，发货类型“补货”
    SELECT TOP 1        -- 目前大部分POS单据不能实现合并成一张单据 老罗注释
            @PosVchcode = a.posvchcode ,
            @HandleManID = a.salesman ,
            @Etypeid = a.cashier ,
            @Btypeid = ISNULL(a.btypeid, '') ,
            @KtypeId = ISNULL(a.ktypeid, '') ,
            @KtypeId2 = ISNULL(a.ktypeid2, '') ,
            @VipCardID = a.VipCardId ,
            @PosUserCode = a.BillCode ,
            @BillDate = CONVERT(VARCHAR(10), CASE WHEN YEAR(a.CheckOutDate) < 2000
                                                  THEN a.saledate
                                                  WHEN vtypeid IN ( '00008',
                                                              '00009' )
                                                  THEN a.SaleDate
                                                  ELSE a.CheckOutDate
                                             END, 120) ,
            @VchType = CASE WHEN vtypeid = '00001' THEN 12
                            WHEN vtypeid = '00002' THEN 0   --暂时代替
                            WHEN vtypeid = '00003' THEN 0   --暂时代替
                            WHEN vtypeid = '00004' THEN 221
                            WHEN vtypeid = '00005' THEN 223
                            WHEN vtypeid = '00006' THEN 0   --暂时代替
                            WHEN vtypeid = '00007' THEN 0   --暂时代替
                            WHEN vtypeid = '00008' THEN 17
                            WHEN vtypeid = '00009' THEN 218
                            ELSE 0
                       END ,
            @Branchid = JTypeId ,
            @Keyid = keyid ,
            @Summary = Summary ,
            @Comment = Comment
    FROM    dbo.tpx_SaleIndex a
    WHERE   JTypeId = @ABranchid
            AND CHARINDEX(':' + Keyid + ':', @BillCode) > 0  

    SELECT TOP 1
            @Period = ISNULL(SubValue, 0)
    FROM    SysData
    WHERE   SubName = 'Period'  

    SELECT TOP 1
            @VipCardPay = COUNT(1)
    FROM    dbo.tpx_SaleVipList
    WHERE   CHARINDEX(':' + zbKeyid + ':', @BillCode) > 0  
    IF @KtypeId2 <> '' 
        SELECT TOP 1
                @Branchid2 = BranchID
        FROM    stock
        WHERE   typeid = @ktypeid
    SELECT TOP 1
            @SubValue = ISNULL(CashAsBillMoney, '0') ,
            @BranchType = BranchType ,
            @CheckAndAccept = CheckAndAccept
    FROM    dbo.Branch
    WHERE   branchid = @Branchid

    
    DECLARE @tmpName VARCHAR(100)
    DECLARE @tmpName1 VARCHAR(100)
    
    IF @HandleManID = ''
        OR @HandleManID IS NULL 
        BEGIN    
		--
            SELECT TOP 1
                    @HandleManID = b.etypeid
            FROM    dbo.tpx_SaleList a
                    INNER JOIN tpx_SaleManList b ON a.keyid = b.CBKeyId
            WHERE   ZBKeyId = @keyid
        END
    SET @tmpHandleManID = @HandleManID
    SET @tmpetypeid = @Etypeid
    SET @tmpVipCardID = @VipCardID
    SET @BakMoneySum = 0

    DECLARE @tmpPtypeid VARCHAR(100)

    SET @tmpCodeStr = @BillCode
    SELECT TOP 1
            @Dtypeid = Dtypeid
    FROM    dbo.Employee
    WHERE   TypeId = @HandleManID --取职员所属部门的ID
    
    DECLARE @dig_qty INT ,
        @dig_price INT ,
        @dig_total INT ,
        @dig_dis INT ,
        @dig_tax INT ,
        @dig_rate INT
    EXEC GetDig @dig_qty OUTPUT, @dig_price OUTPUT, @dig_total OUTPUT,
        @dig_dis OUTPUT, @dig_tax OUTPUT, @dig_rate OUTPUT


    BEGIN TRAN
    BEGIN TRY 
		--获取内部机构或加盟机构现金、银行卡、代金券对应科目及税率
        DECLARE @ACash VARCHAR(50)
        DECLARE @ACard VARCHAR(50)
        DECLARE @ATicket VARCHAR(50)
        DECLARE @TaxRate NUMERIC(24, 10)= 0.00
        IF @BranchType <> 3 
            BEGIN
                SELECT TOP 1
                        @ACash = ATypeId
                FROM    dbo.tpx_PosCashTypeConfig
                WHERE   Jtypeid = @ABranchid
                        AND Keyid = '00001'
                SELECT TOP 1
                        @ACard = ATypeId
                FROM    dbo.tpx_PosCashTypeConfig
                WHERE   Jtypeid = @ABranchid
                        AND Keyid = '00002'
                SELECT TOP 1
                        @ATicket = ATypeId
                FROM    dbo.tpx_PosCashTypeConfig
                WHERE   Jtypeid = @ABranchid
                        AND Keyid = '00003'
                SELECT TOP 1
                        @Tax = ROUND(Rate, @dig_tax)
                FROM    dbo.tpx_PosCashMain
                WHERE   Jtypeid = @ABranchid
					
            END
        IF @Summary = '' 
            SET @tmpName1 = '前台POS小票【' + @PosUserCode + '】'
        ELSE 
            SET @tmpName1 = @Summary
	    
        IF @ConditionStr = 'ht' 
            SET @tmpName1 = @tmpName1 + '，后台结存生成！'
	    
        IF @PosVchcode <> 0
            AND @VchType = 12 
            BEGIN

                IF @BranchType = 1
                    OR @BranchType = 7
                    OR @BranchType = 4 
                    SET @VchType = 12	-- 零售单
	                
                IF @BranchType = 3 
                    BEGIN
                        SET @VchType = 100	-- 代销零售单
                        SET @Tax = 0--代销零售单税率默认为0，再通过以面一句脚本更新（可能BtypeDistribute此机构的信息就会使用这个默认值0）                   
                        SELECT  @Tax = bd.TaxRate
                        FROM    Branch b
                                INNER JOIN dbo.BtypeDistribute bd ON b.Branchid = @Branchid
                                                              AND bd.BtypeId = b.BtypeId
                    END
	            
	           
                SET @Tax = ISNULL(@Tax, 0)
				--得到单据Number
                EXEC FN_VchNumber_Get @VchType, @BillDate, @ABranchid,
                    '127.0.0.1', 1, @Number OUTPUT

				-- 增加一个主表
                EXEC @VchCode = FZInsertDlyNdx 2, --Billtype 
                    @BillDate, -- @date
                    @Number, -- @number
                    @VchType, -- @vchtype
                    @tmpName1, -- @summary
                    @Comment, -- @comment
                    @Btypeid, -- @Btypeid
                    @tmpHandleManID, -- @Etypeid
                    @KtypeId, -- @KtypeId
                    '', -- @KtypeId2
                    0, -- @ifcheck
                    '', -- @checke
                    '', -- @accounte              
                    @tmpetypeid, -- @inputno
                    10, -- @draft
                    @tmpVipCardId, -- @vipcardid
                    100, -- @vipdiscount
                    0, -- @bartertype
                    @Dtypeid, -- @deptid
                    @BillDate, -- @limittime
                    '', -- @inputno1
                    '', -- @inputno2
                    '', -- @inputno3
                    100, -- @zddiscount
                    0, -- @zddiscountprice
                    0, -- @preferential
                    '', --@InputNo4
                    '', --@InputNo5
                    '', --科目ID
                    0, --@AtypeTotal 
                    '', --@ExpandId
                    '', --@ZoneId
                    '', --@ZoneId2
                    @site, -- @SiteId
                    @Branchid
				IF @VchCode<0 
				BEGIN
					  ROLLBACK TRAN
					  IF @VchCode<>-1
					  	  RETURN -3
					  ELSE
						  RETURN -1
				END
				--占用account字段设置POS小票生成草稿的标志，占用backmoney字段用来记录公共POS的单据积分金额
                UPDATE  DlyNdx
                SET     account = 'COMMONPOSLSJC' ,
                        BackMoney = ( SELECT    SUM(VipIntegral) AS jfje
                                      FROM      dbo.tpx_SaleIndex a
                                      WHERE     a.JTypeId = @ABranchid
                                                AND CHARINDEX(':' + keyid
                                                              + ':', @BillCode) > 0
                                    )
                WHERE   VchCode = @VchCode
    
  
                SELECT  a.ColorID ,	         SUM(a.DisCount) DisCount ,
				        a.DisCountRate ,    a.Price ,        a.PtypeID ,		   
				        SUM(a.Qty) Qty ,	a.RetailPrice ,  a.SizeID ,	  
				        SUM( a.Total )  Total ,
				        a.UnitId 
				        INTO  #tpx_SaleList_temp   
			    FROM    dbo.tpx_SaleList a
                        WHERE   CHARINDEX(':' + a.zbkeyid + ':', @tmpCodeStr) > 0
			    GROUP BY  a.ColorID ,	   
				        a.DisCountRate ,    a.Price ,       a.PtypeID ,			      
				        a.RetailPrice ,     		        a.SizeID ,	      
				        a.UnitId 
				HAVING  SUM(a.Qty)<>0 AND SUM( a.Total )<>0       
                     
                INSERT  INTO [dbo].[bakdly]
                        ( [vchcode] ,
                          [atypeId] ,
                          [btypeId] ,
                          [etypeId] ,
                          [ktypeId] ,
                          [branchid] ,
                          vipcardid ,
                          billtype ,
                          RetailPrice ,
                          [PtypeId] ,
                          [Qty] ,
                          [discount] ,
                          [discountprice] ,
                          [costtotal] ,
                          [costPrice] ,
                          [price] ,
                          [total] ,
                          [TaxPrice] ,
                          [TaxTotal] ,
                          [comment] ,
                          [date] ,
                          [usedtype] ,
                          [period] ,
                          [tax_total] ,
                          [tax] ,
                          [discounttotal] ,
                          [costmode] ,
                          [vchtype] ,
                          [Dtypeid] ,
                          [colorid] ,
                          [VipDiscount] ,
                          [convert] ,
                          [roworder] ,
                          [bargainTotal] ,
                          [ifSupply] ,
                          [SaleMoney] ,
                          [MarketDiscount] ,
                          [MarketDiscount1] ,
                          [salemode] ,
                          [PHRows]
						)
                        SELECT  @VchCode ,
                                '0000100001' ,
                                @Btypeid ,
                                @tmpHandleManID ,
                                @KtypeId ,
                                @Branchid ,
                                @tmpVipCardId ,
                                2 ,
                                RetailPrice ,
                                Ptypeid ,
                                SUM(Qty) ,
                                100 ,
                                RetailPrice ,
                                0 ,
                                0 ,
                                RetailPrice ,
                                0 ,----total
                                CASE @BranchType
                                  WHEN 3
                                  THEN ROUND(ISNULL(SUM(a.Total), 0) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100
                                             / ( CASE WHEN SUM(Qty) = 0 THEN 1
                                                      ELSE SUM(qty)
                                                 END ), @dig_price)
                                  ELSE ROUND(ISNULL(SUM(a.Total), 0)
                                             / ( CASE WHEN SUM(Qty) = 0 THEN 1
                                                      ELSE SUM(qty)
                                                 END ), @dig_price)                --税价
                                END ,
                                0 ,--税额----TaxTotal 
                                '' ,
                                @BillDate ,
                                1 ,
                                @Period ,
                                CASE @BranchType
                                  WHEN 3
                                  THEN ROUND(SUM(ISNULL(a.Total, 0)) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100,
                                             @dig_total)
                                  ELSE ROUND(SUM(ISNULL(a.Total, 0)),
                                             @dig_total)	       -- 含税金额 -----POS 那边的Total 是含税的 tax_total
                                END ,
                                ISNULL(@Tax, 0.00) ,
                                price ,  -- discounttotal 本来这里该直接写0 此处暂借用来写折后价，
										 --	是为了Group by ,不然插bakdlydetail时就要失去关联
										 -- 在后面要更正的
                                0 ,
                                @VchType ,
                                '' ,--dtypeid
                                ColorID ,
                                100 ,--vipdiscount
                                0 ,--convert
                                0 ,
                                0 ,-- 成交金额 扣税-----bargainTotal
                                0 ,
                                0 , ------Salemoney
                                CASE @BranchType
                                  WHEN 3
                                  THEN ISNULL(( SELECT  b.Price
                                                FROM    ptypeprice b
                                                WHERE   b.ptypeId = a.ptypeid
                                                        AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                              ), 0)
                                  ELSE 0
                                END ,
                                CASE @BranchType
                                  WHEN 3
                                  THEN ISNULL(( SELECT  b.Price
                                                FROM    ptypeprice b
                                                WHERE   b.ptypeId = a.ptypeid
                                                        AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                              ), 0)
                                  ELSE 0
                                END ,
                                0 ,
                                ROW_NUMBER() OVER ( ORDER BY ColorID ) --获得行号，对应PHrows字段
                        FROM   #tpx_SaleList_temp
                        GROUP BY Ptypeid ,
                                RetailPrice ,
                                price ,
                                ColorID ,
                                SIGN(QTY)
                --写三级明细                
            	-----*******************************************测试用    
                --SELECT *FROM bakdly WHERE vchcode=@VchCode
                --SELECT  b.DlyOrder ,
                --                a.SizeID ,
                --                a.ColorID ,
                --                SUM(a.Qty) AS qty ,
                --                0 ,
                --                ROUND(CAST(CAST(SUM(a.Qty) AS NUMERIC(24,10)) * a.RetailPrice AS NUMERIC(24,10)), @dig_total) ,----total
                --                CASE @BranchType
                --                  WHEN 3
                --                  THEN ROUND(CAST(Cast(SUM(a.Total) AS NUMERIC(24,10)) * ( 100
                --                                              - ISNULL(( SELECT
                --                                              b.Price
                --                                              FROM
                --                                              ptypeprice b
                --                                              WHERE
                --                                              b.ptypeId = a.ptypeid
                --                                              AND b.PriceTypeId = ( SELECT
                --                                              c.MarketDiscountID
                --                                              FROM
                --                                              btypedistribute c
                --                                              WHERE
                --                                              c.btypeid = @Btypeid
                --                                              )
                --                                              ), 0) ) / 100 AS NUMERIC(24,10)),
                --                             @dig_total)
                --                       - ROUND(CAST(Cast(SUM(a.Total) AS NUMERIC(24,10) ) * ( 100
                --                                              - ISNULL(( SELECT
                --                                              b.Price
                --                                              FROM
                --                                              ptypeprice b
                --                                              WHERE
                --                                              b.ptypeId = a.ptypeid
                --                                              AND b.PriceTypeId = ( SELECT
                --                                              c.MarketDiscountID
                --                                              FROM
                --                                              btypedistribute c
                --                                              WHERE
                --                                              c.btypeid = @Btypeid
                --                                              )
                --                                              ), 0) ) / 100
                --                               / ( 1 + ISNULL(@Tax, 0) / 100 ) AS NUMERIC(24,10)),
                --                               @dig_total)
                --                  ELSE ROUND(cast(SUM(a.Total) AS NUMERIC(24,10)),
                --                             @dig_total)
                --                       - ROUND(CAST(Cast(SUM(a.Total) AS NUMERIC(24,10) ) / ( 1
                --                                              + @TaxRate / 100 ) AS NUMERIC(24,10)),
                --                               @dig_total)
                --                END ,  --税额----TaxTotal 
                --                CASE @BranchType
                --                  WHEN 3
                --                  THEN ROUND(CAST(Cast(SUM(a.Total) AS NUMERIC(24,10) ) * ( 100
                --                                              - ISNULL(( SELECT
                --                                              b.Price
                --                                              FROM
                --                                              ptypeprice b
                --                                              WHERE
                --                                              b.ptypeId = a.ptypeid
                --                                              AND b.PriceTypeId = ( SELECT
                --                                              c.MarketDiscountID
                --                                              FROM
                --                                              btypedistribute c
                --                                              WHERE
                --                                              c.btypeid = @Btypeid
                --                                              )
                --                                              ), 0) ) / 100 AS NUMERIC(24,10)),
                --                             @dig_total)
                --                  ELSE ROUND(ISNULL(SUM(a.Total), 0),
                --                             @dig_total)
                --                END ,-- 含税金额 -----tax_total
                --                CASE @BranchType
                --                  WHEN 3
                --                  THEN ROUND(CAST(Cast(SUM(a.Total) as numeric(24,10)) * ( 100
                --                                              - ISNULL(( SELECT
                --                                              b.Price
                --                                              FROM
                --                                              ptypeprice b
                --                                              WHERE
                --                                              b.ptypeId = a.ptypeid
                --                                              AND b.PriceTypeId = ( SELECT
                --                                              c.MarketDiscountID
                --                                              FROM
                --                                              btypedistribute c
                --                                              WHERE
                --                                              c.btypeid = @Btypeid
                --                                              )
                --                                              ), 0) ) / 100
                --                             / ( 1 + @Tax / 100 ) AS NUMERIC(24,10)), @dig_total)
                --                  ELSE ROUND(Cast(Cast(SUM(a.Total) AS NUMERIC(24,10)) / ( 1
                --                                              + @TaxRate / 100 ) AS NUMERIC(24,10)),
                --                             @dig_total)
                --                END ,---BargainTotal =含税金额/(1+税率/100)
                --                CASE @BranchType
                --                  WHEN 3
                --                  THEN ----
                --                       ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24,10)) *a.RetailPrice AS NUMERIC(24,10)),
                --                             @dig_total) - ISNULL(SUM(a.Total),
                --                                              0)
                --                  ELSE ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24,10)) *a.RetailPrice AS NUMERIC(24,10)),
                --                             @dig_total)
                --                       - ROUND(Cast(Cast(SUM(a.Total) AS NUMERIC(24,10)) / ( 1
                --                                              + @Tax / 100 ) AS NUMERIC(24,10)),
                --                               @dig_total)
                --                END ,--convert
                --                ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24,10)) *a.RetailPrice AS NUMERIC(24,10)), @dig_total) ,--DiscountTotal
                --                ISNULL(SUM(a.Total), 0) , --salemoney
                --                1 ,
                --                b.PHRows ,
                --                @VchCode
                --        FROM    dbo.tpx_SaleList a
                --                INNER JOIN bakdly b ON a.Ptypeid = b.Ptypeid
                --                                       AND a.RetailPrice = b.Price
                --                                       AND a.ColorID = B.ColorID
                --                                       AND a.price = b.discounttotal
                --                                       AND b.Vchcode = @VchCode
                --                                       --AND SIGN(SUM(a.QTY))=SIGN(b.qty)
                --        WHERE   CHARINDEX(':' + a.ZBKeyId + ':', @tmpCodeStr) > 0
                --        GROUP BY a.ptypeid ,
                --                a.ColorID ,
                --                a.SizeID ,
                --                b.DlyOrder ,
                --                a.RetailPrice ,
                --                a.price,
                --                SIGN(a.qty),
                --                b.qty, 
                --                b.PHRows     
                --        HAVING  SIGN(SUM(a.QTY))=SIGN(b.qty)          
                ----*******************************************测试用
                INSERT  INTO bakDlydetail
                        ( dlyorder ,
                          sizeid ,
                          colorid ,
                          Qty ,
                          CostTotal ,
                          Total ,
                          TaxTotal ,
                          Tax_Total ,
                          BargainTotal ,
                          [Convert] ,
                          DiscountTotal ,
                          SaleMoney ,
                          Usedtype ,
                          PHRows ,
                          Vchcode
						)
                        SELECT  b.DlyOrder ,
                                a.SizeID ,
                                a.ColorID ,
                                SUM(a.Qty) AS qty ,
                                0 ,
                                ROUND(CAST(CAST(SUM(a.Qty) AS NUMERIC(24, 10))
                                      * a.RetailPrice AS NUMERIC(24, 10)),
                                      @dig_total) ,----total
                                CASE @BranchType
                                  WHEN 3
                                  THEN ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100 AS NUMERIC(24,
                                                              10)), @dig_total)
                                       - ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100
                                               / ( 1 + ISNULL(@Tax, 0) / 100 ) AS NUMERIC(24,
                                                              10)), @dig_total)
                                  ELSE ROUND(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)), @dig_total)
                                       - ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) / ( 1
                                                              + @Tax / 100 ) AS NUMERIC(24,
                                                              10)), @dig_total)
                                END ,  --税额----TaxTotal 
                                CASE @BranchType
                                  WHEN 3
                                  THEN ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100 AS NUMERIC(24,
                                                              10)), @dig_total)
                                  ELSE ROUND(ISNULL(SUM(a.Total), 0),
                                             @dig_total)
                                END ,-- 含税金额 -----tax_total
                                CASE @BranchType
                                  WHEN 3
                                  THEN ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100
                                             / ( 1 + @Tax / 100 ) AS NUMERIC(24,
                                                              10)), @dig_total)
                                  ELSE ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) / ( 1
                                                              + @Tax / 100 ) AS NUMERIC(24,
                                                              10)), @dig_total)
                                END ,---BargainTotal =含税金额/(1+税率/100)
                                CASE @BranchType
                                  WHEN 3
                                  THEN ----
                                       ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24,
                                                              10))
                                             * a.RetailPrice AS NUMERIC(24, 10)),
                                             @dig_total) - ISNULL(SUM(a.Total),
                                                              0)
                                  ELSE ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24,
                                                              10))
                                             * a.RetailPrice AS NUMERIC(24, 10)),
                                             @dig_total)
                                       - ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) / ( 1
                                                              + @Tax / 100 ) AS NUMERIC(24,
                                                              10)), @dig_total)
                                END ,--convert
                                ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24, 10))
                                      * a.RetailPrice AS NUMERIC(24, 10)),
                                      @dig_total) ,--DiscountTotal
                                ISNULL(ROUND(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)), @dig_total),
                                       0) , --salemoney
                                1 ,
                                b.PHRows ,
                                @VchCode
                        FROM    #tpx_SaleList_temp a
                                INNER JOIN bakdly b ON a.Ptypeid = b.Ptypeid
                                                       AND a.RetailPrice = b.Price
                                                       AND a.ColorID = B.ColorID
                                                       AND a.price = b.discounttotal
                                                       AND b.Vchcode = @VchCode
                                                       --AND SIGN(SUM(a.QTY))=SIGN(b.qty)
                        GROUP BY a.ptypeid ,
                                a.ColorID ,
                                a.SizeID ,
                                b.DlyOrder ,
                                a.RetailPrice ,
                                a.price ,
                                SIGN(a.qty) ,
                                b.qty ,
                                b.PHRows
                        HAVING  SIGN(SUM(a.QTY)) = SIGN(b.qty)          
                       
	                             
                IF EXISTS ( SELECT  1            --POS小票类单据生成总部草稿以后，更改POS小票类单据的状态
                            FROM    dbo.tpx_SaleIndex
                            WHERE   draftvchCode > 0
                                    AND CHARINDEX(':' + keyid + ':',
                                                  @tmpCodeStr) > 0 ) 
                    GOTO error1  
                ELSE 
                    UPDATE  dbo.tpx_SaleIndex
                    SET     draftvchCode = @VchCode
                    WHERE   Jtypeid = @ABranchid
                            AND CHARINDEX(':' + keyid + ':', @tmpCodeStr) > 0      
				--此处收款科目是动态的，根据用户设置可能有很多种以前的老代码删除了 modify by 老罗 2012-11-12
 
				-- 写收款科目

                IF ( @VchType = 12
                     OR @VchType = 13
                   )
                    AND @RetailSum <> 0
                    AND @SubValue = '1' 
                    UPDATE  dbo.DlyNdx
                    SET     AtypeTotal = ISNULL(@RetailSum, 0)
                    WHERE   VchCode = @VchCode
			   -- modify by 老罗 2012-11-12 因为是动态的科目，所以直接取pos的付款方式表tpx_salepaylist中记录
	   
                IF @BranchType <> 3 
                    BEGIN
                        IF EXISTS ( SELECT  1
                                    FROM    dbo.tpx_SalePayList
                                    WHERE   CHARINDEX(':' + ZBkeyid + ':',
                                                      @tmpCodeStr) > 0 ) 
                            BEGIN
                                INSERT  INTO [dbo].[bakdly]
                                        ( [vchcode] ,
                                          [atypeId] ,
                                          [btypeId] ,
                                          [etypeId] ,
                                          [ktypeId] ,
                                          [PtypeId] ,
                                          [branchid] ,
                                          [billtype ] ,
                                          [Qty] ,
                                          [discount] ,
                                          [discountprice] ,
                                          [costtotal] ,
                                          [costPrice] ,
                                          [price] ,
                                          [total] ,
                                          [TaxPrice] ,
                                          [TaxTotal] ,
                                          [comment] ,
                                          [date] ,
                                          [usedtype] ,
                                          [period] ,
                                          [tax_total] ,
                                          [tax] ,
                                          [discounttotal] ,
                                          [costmode] ,
                                          [vchtype] ,
                                          [unit] ,
                                          [Dtypeid] ,
                                          [colorid] ,
                                          [VipDiscount] ,
                                          [convert] ,
                                          [roworder] ,
                                          [bargainTotal] ,
                                          [ifSupply]
									    )
                                        SELECT  @VchCode ,
                                                p.AtypeId ,
                                                @Btypeid ,
                                                @tmpetypeid ,
                                                @KtypeId ,
                                                '' ,
                                                @branchid ,
                                                2 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                SUM(Total) ,
                                                0 ,
                                                0 ,
                                                CASE WHEN p.Keyid='00003' THEN 'systemDJQ' ELSE '' END,
                                                @BillDate ,
                                                '2' ,
                                                @Period ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                @VchType ,
                                                0 ,
                                                '' ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0
                                        FROM    dbo.tpx_SalePayList s
                                                INNER JOIN dbo.tpx_PosCashTypeConfig p ON s.akeyid = p.keyid
                                                              AND p.Jtypeid = @Branchid
                                        WHERE   CHARINDEX(':' + s.ZBkeyid
                                                          + ':', @tmpCodeStr) > 0
                                                AND s.AKeyId <> '00004'
                                        GROUP BY p.AtypeId ,p.Keyid                   
                                
                            END 
                        IF ABS(@vipcardpay) > 0 
                            BEGIN
                                INSERT  INTO [dbo].[bakdly]
                                        ( [vchcode] ,
                                          [atypeId] ,
                                          [btypeId] ,
                                          [etypeId] ,
                                          [ktypeId] ,
                                          [PtypeId] ,
                                          [branchid] ,
                                          vipcardid ,
                                          billtype ,
                                          [Qty] ,
                                          [discount] ,
                                          [discountprice] ,
                                          [costtotal] ,
                                          [costPrice] ,
                                          [price] ,
                                          [total] ,
                                          [TaxPrice] ,
                                          [TaxTotal] ,
                                          [comment] ,
                                          [date] ,
                                          [usedtype] ,
                                          [period] ,
                                          [tax_total] ,
                                          [tax] ,
                                          [discounttotal] ,
                                          [costmode] ,
                                          [vchtype] ,
                                          [unit] ,
                                          [Dtypeid] ,
                                          [colorid] ,
                                          [VipDiscount] ,
                                          [convert] ,
                                          [roworder] ,
                                          [bargainTotal] ,
                                          [ifSupply]
										)
                                        SELECT  @VchCode ,
                                                '0000299999' ,
                                                @Btypeid ,
                                                @tmpetypeid ,
                                                @KtypeId ,
                                                '' ,
                                                @branchid ,
                                                vipid ,
                                                2 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                CASE WHEN SIGN(c.FinallyTotal) >= 0
                                                     THEN a.Total
                                                     ELSE -1 * a.Total
                                                END ,
                                                0 ,
                                                0 ,
                                                '卡号:' + cardno + ' 持卡人:'
                                                + holderName ,
                                                @BillDate ,
                                                '2' ,
                                                @Period ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                @VchType ,
                                                0 ,
                                                '' ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0
                                        FROM    dbo.tpx_SaleVipList a
                                                INNER JOIN dbo.tpx_SaleIndex c ON a.ZBKeyId = c.keyId
                                                LEFT JOIN vipcards b ON a.vipid = b.cardid
                                        WHERE   CHARINDEX(':' + a.ZBKeyId
                                                          + ':', @tmpCodeStr) > 0 
                              
                            END
                    END
				
                       
	                   
                UPDATE  bakdly
                SET     total = b.total ,
                        TaxTotal = b.TaxTotal ,
                        Tax_Total = b.Tax_Total ,
                        BargainTotal = b.BargainTotal ,
                        [Convert] = b.[Convert] ,
                        DiscountTotal = b.DiscountTotal ,
                        SaleMoney = b.SaleMoney
                FROM    bakdly a ,
                        ( SELECT    DlyOrder ,
                                    ROUND(CAST(SUM(total) AS NUMERIC(24, 10)),
                                          @dig_total) AS total ,
                                    ROUND(CAST(SUM(TaxTotal) AS NUMERIC(24, 10)),
                                          @dig_Total) AS TaxTotal ,
                                    ROUND(CAST(SUM(Tax_Total) AS NUMERIC(24,
                                                              10)), @dig_total) AS Tax_Total ,
                                    ROUND(CAST(SUM(BargainTotal) AS NUMERIC(24,
                                                              10)), @dig_total) AS BargainTotal ,
                                    ROUND(CAST(SUM([Convert]) AS NUMERIC(24,
                                                              10)), @dig_total) AS [Convert] ,
                                    ROUND(CAST(SUM(DiscountTotal) AS NUMERIC(24,
                                                              10)), @dig_total) AS DiscountTotal ,
                                    ROUND(CAST(SUM(SaleMoney) AS NUMERIC(24,
                                                              10)), @dig_total) AS SaleMoney
                          FROM      bakdlydetail
                          WHERE     vchcode = @VchCode
                          GROUP BY  DlyOrder
                        ) AS b
                WHERE   a.vchcode = @VchCode
                        AND a.dlyorder = b.dlyorder 
	            
                UPDATE  a
                SET     a.phrows = b.phrows
                FROM    bakdlydetail a
                        INNER JOIN bakdly b ON a.vchcode = b.vchcode
                                               AND a.DlyOrder = b.DlyOrder
                WHERE   a.vchcode = @VchCode
	            
                UPDATE  dbo.DlyNdx
                SET     qty = ROUND(ISNULL(b.qty, 0.00), @dig_qty) ,
                        total = ROUND(ISNULL(b.total, 0.00), @dig_total)
                FROM    dlyndx a ,
                        ( SELECT    Vchcode ,
                                    CAST(SUM(qty) AS NUMERIC(24, 10)) AS qty ,
                                    CAST(SUM(SaleMoney) AS NUMERIC(24, 10)) AS total
                          FROM      bakdly
                          WHERE     UsedType = 1
                                    AND vchcode = @VchCode
                          GROUP BY  Vchcode
                        ) AS b
                WHERE   a.Vchcode = b.Vchcode
                        AND a.Vchcode = @VchCode
     --           --特殊处理只在结算时录入vip卡的情况（取结算第一张卡的卡号作为主表的vip卡） 此处pos端处理了
     --           IF exists(SELECT 1 FROM bakdly a INNER JOIN dlyndx d ON a.vchcode=d.vchcode 
					--	  WHERE a.VipCardID<>0 AND d.VipCardID=0 AND d.vchcode=@VchCode)
			  --  BEGIN
					--UPDATE a SET a.vipcardid=b.vipcardid FROM dlyndx a INNER JOIN 
					--	(select TOP 1 VipCardID,vchcode FROM bakdly WHERE VipCardID<>0 AND vchcode=@VchCode) b 
					--		ON a.vchcode=b.vchcode
					--WHERE b.VipCardID<>0 AND a.VipCardID=0 AND a.vchcode=@VchCode
			  --  END
                      
                --特殊处理代金卷的问题 (零售单一定会收款)
                
                IF EXISTS ( SELECT TOP 1
                                    1
                            FROM    bakdly
                            WHERE   Vchcode = @VchCode
                                    AND Comment = 'systemDJQ' ) 
                    BEGIN
                        IF EXISTS ( SELECT  SUM(Total)
                                    FROM    ( SELECT    SUM(CASE
                                                              WHEN ( NOT ptypeid IS NULL
                                                              AND ptypeid <> ''
                                                              )
                                                              THEN -salemoney
                                                              ELSE Total
                                                            END) AS Total ,
                                                        ptypeid ,
                                                        SUM(qty) qty
                                              FROM      bakdly
                                              WHERE     Vchcode = @VchCode
                                              GROUP BY  ptypeid
                                            ) c
                                    HAVING  SUM(Total) > 0
                                            AND SUM(qty) >= 0 ) 
                            BEGIN
                                UPDATE  a
                                SET     a.Total = a.Total - b.Total
                                FROM    bakdly a ,
                                        ( SELECT    SUM(Total) Total ,
                                                    vchcode
                                          FROM      ( SELECT  SUM(CASE
                                                              WHEN ( NOT ptypeid IS NULL
                                                              AND ptypeid <> ''
                                                              )
                                                              THEN -salemoney
                                                              ELSE Total
                                                              END) AS Total ,
                                                              ptypeid ,
                                                              Vchcode ,
                                                              SUM(qty) qty
                                                      FROM    bakdly
                                                      WHERE   Vchcode = @VchCode
                                                      GROUP BY ptypeid ,
                                                              vchcode
                                                    ) c
                                          GROUP BY  vchcode
                                          HAVING    SUM(Total) > 0
                                                    AND SUM(qty) >= 0
                                        ) b
                                WHERE   a.Vchcode = @VchCode
                                        AND a.Vchcode = b.vchcode
                                        AND a.Comment = 'systemDJQ'
                            END    
                        IF EXISTS ( SELECT  SUM(Total)
                                    FROM    ( SELECT    SUM(CASE
                                                              WHEN ( NOT ptypeid IS NULL
                                                              AND ptypeid <> ''
                                                              )
                                                              THEN -salemoney
                                                              ELSE Total
                                                            END) AS Total ,
                                                        ptypeid ,
                                                        SUM(qty) AS qty
                                              FROM      bakdly
                                              WHERE     Vchcode = @VchCode
                                              GROUP BY  ptypeid
                                            ) c
                                    HAVING  SUM(Total) < 0
                                            AND SUM(qty) <= 0 ) 
                            BEGIN
                                UPDATE  a
                                SET     a.Total = a.Total - b.Total
                                FROM    bakdly a ,
                                        ( SELECT    SUM(Total) Total ,
                                                    vchcode
                                          FROM      ( SELECT  SUM(CASE
                                                              WHEN ( NOT ptypeid IS NULL
                                                              AND ptypeid <> ''
                                                              )
                                                              THEN -salemoney
                                                              ELSE Total
                                                              END) AS Total ,
                                                              ptypeid ,
                                                              vchcode ,
                                                              SUM(qty) qty
                                                      FROM    bakdly
                                                      WHERE   Vchcode = @VchCode
                                                      GROUP BY ptypeid ,
                                                              vchcode
                                                    ) c
                                          GROUP BY  vchcode
                                          HAVING    SUM(Total) < 0
                                                    AND SUM(qty) <= 0
                                        ) b
                                WHERE   a.Vchcode = @VchCode
                                        AND a.Vchcode = b.vchcode
                                        AND a.Comment = 'systemDJQ'
                            END    
                    END
            END
		-- 新增一个调拨或配送单草稿
	    
        IF @PosVchcode <> 0
            AND @VchType IN ( 17, 218 ) 
            BEGIN
		
			 --得到单据Number
				
                EXEC FN_VchNumber_Get @VchType, @BillDate, @ABranchid,
                    '127.0.0.1', 1, @Number OUTPUT

				--判断是否启用配送验收流程 配送单过账的时候要判断此处不用了2012-10-29
				--DECLARE @VerifyFlow BIT
				--SELECT TOP 1 @VerifyFlow=CheckAndAccept FROM dbo.Branch WHERE BranchID=@Branchid2
				-- 增加一个主表
                EXEC @VchCode = FZInsertDlyNdx 3, --Billtype 
                    @BillDate, -- @date
                    @Number, -- @number
                    @VchType, -- @vchtype
                    @tmpName1, -- @summary
                    @comment, -- @comment
                    @Btypeid, -- @Btypeid
                    @tmpHandleManID, -- @Etypeid
                    @KtypeId, -- @KtypeId
                    @Ktypeid2, -- @KtypeId2
                    0, -- @ifcheck
                    '', -- @checke
                    'COMMONPOSLSJC', -- @accounte              
                    @tmpetypeid, -- @inputno
                    10, -- @draft
                    @tmpVipCardId, -- @vipcardid
                    100, -- @vipdiscount
                    0, -- @bartertype
                    @Dtypeid, -- @deptid
                    '', -- @limittime
                    @tmpetypeid, -- @inputno1
                    '', -- @inputno2
                    '', -- @inputno3
                    0, -- @zddiscount
                    0, -- @zddiscountprice
                    0, -- @preferential
                    '', --@InputNo4
                    '', --@InputNo5
                    '', --科目ID
                    0, --@AtypeTotal 
                    '', --@ExpandId
                    '', --@ZoneId
                    '', --@ZoneId2
                    @site, -- @SiteId
                    @Branchid2, 0, --@Total
                    '', --@Xw_Vsf1   
                    '', --@Xw_Vsf2
                    '', --@Xw_Vsf3
                    '', --@Xw_Vsf4
                    '', --@Xw_Vsf5
                    '', --@VchOrderList
                    @BranchId, --@BranchId2
                    3   --@phid
                IF @VchCode<0 
				BEGIN
					  ROLLBACK TRAN
					  IF @VchCode<>-1
					  	  RETURN -3
					  ELSE
						  RETURN -1
				END
                INSERT  INTO [dbo].[bakdly]
                        ( [vchcode] ,
                          [atypeId] ,
                          [btypeId] ,
                          [etypeId] ,
                          [ktypeId] ,
                          [branchid] ,
                          vipcardid ,
                          billtype ,
                          RetailPrice ,
                          [PtypeId] ,
                          [Qty] ,
                          [discount] ,
                          [discountprice] ,
                          [costtotal] ,
                          [costPrice] ,
                          [price] ,
                          [total] ,
                          [TaxPrice] ,
                          [TaxTotal] ,
                          [comment] ,
                          [date] ,
                          [usedtype] ,
                          [period] ,
                          [tax_total] ,
                          [tax] ,
                          [discounttotal] ,
                          [costmode] ,
                          [vchtype] ,
                          [Dtypeid] ,
                          [colorid] ,
                          [VipDiscount] ,
                          [convert] ,
                          [roworder] ,
                          [bargainTotal] ,
                          [ifSupply] ,
                          [SaleMoney] ,
                          [MarketDiscount] ,
                          [MarketDiscount1] ,
                          [salemode] ,
                          [PHRows] ,
                          OpID ,
                          Unit
		                
						)
						--Total,tax_total,bargaintotal,DiscountTotal,salemoney这五种金额直接写当前库存成本价，没有取到则写0
						--二级主表除零售金额和单价以外都写0，写完三级明细后反写二级明细
                        SELECT  @VchCode ,
                                '0000100001' ,
                                @Btypeid ,
                                @tmpHandleManID ,
                                @KtypeId ,
                                @Branchid2 ,
                                @tmpVipCardId ,
                                3 ,
                                RetailPrice ,
                                Ptypeid ,
                                SUM(Qty) ,
                                100 ,          --discount
                                0 ,            --discountprice   
                                0 ,            --costTotal
                                0 ,            --Costprice
                                0 ,            --price
                                0 ,            --total
                                0 ,            --Taxprice
                                0 ,            --TaxTotal 税额---- 
                                a.Comment ,
                                @BillDate ,
                                1 ,            --usedtype
                                @Period ,            --[period]
                                0 ,              --tax_total  含税金额 ---
                                ISNULL(@Tax, 0) ,--Tax
                                0 ,          -- discounttotal 
                                0 ,              --Costmode
                                @VchType ,
                                @dtypeid ,       --Dtypeid
                                ColorID ,
                                100 ,            --vipdiscount
                                0 ,              --convert
                                0 ,              --roworder
                                0 ,              --bargainTotal 成交金额 扣税-----
                                0 ,              --ifSupply
                                0 ,              --Salemoney
                                100 ,            --MarketDiscount  配送和调拨不用考虑商场扣率问题
                                100 ,            --MarketDiscount1
                                0 ,
                                ROW_NUMBER() OVER ( ORDER BY ColorID ) , --获得行号，对应PHrows字段
                                3 ,
                                a.Unitid
                        FROM    dbo.tpx_ReplenishList a
                        WHERE   CHARINDEX(':' + a.zbkeyid + ':', @tmpCodeStr) > 0
                        GROUP BY Ptypeid ,
                                RetailPrice ,
                                ColorID ,
                                a.Unitid ,
                                a.Comment
	                             
                IF EXISTS ( SELECT  1
                            FROM    dbo.tpx_SaleIndex
                            WHERE   draftvchCode > 0
                                    AND CHARINDEX(':' + keyid + ':',
                                                  @tmpCodeStr) > 0 ) 
                    GOTO error1  
                ELSE 
                    UPDATE  dbo.tpx_SaleIndex
                    SET     draftvchCode = @VchCode
                    WHERE   Jtypeid = @ABranchid
                            AND CHARINDEX(':' + keyid + ':', @tmpCodeStr) > 0      
	-----*******************************************测试用			
				--SELECT *FROM bakdly WHERE Vchcode=@VchCode
				--SELECT  b.DlyOrder ,
    --                            a.SizeID ,
    --                            a.ColorID ,
    --                            SUM(a.Qty) AS qty ,
    --                            0 ,
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) ,----total
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) ,--税额----TaxTotal 
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) , -- 含税金额 -----tax_total
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) , ---BargainTotal
    --                            0 ,
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) ,--DiscountTotal
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) , --SaleMoney
    --                            1 ,
    --                            b.PHRows ,
    --                            @VchCode
    --                    FROM    dbo.tpx_ReplenishList a
    --                            INNER JOIN bakdly b ON a.Ptypeid = b.Ptypeid
    --                                                   AND b.Vchcode = @VchCode
    --                                                   AND a.ColorID = B.ColorID
    --                                                   AND a.Comment=b.Comment
    --                            LEFT JOIN Goodsstocks g ON b.ktypeid = g.KtypeId
    --                                                       AND b.PtypeId = g.PtypeId
    --                    WHERE   CHARINDEX(':' + a.ZBKeyId + ':', @tmpCodeStr) > 0
    --                    GROUP BY a.ptypeid ,
    --                            a.ColorID ,
    --                            a.SizeID ,
    --                            b.DlyOrder ,
    --                            g.price ,
    --                            a.Comment,
    --                            b.PHRows
    -----*******************************************测试用
                INSERT  INTO bakDlydetail
                        ( dlyorder ,
                          sizeid ,
                          colorid ,
                          Qty ,
                          CostTotal ,
                          Total ,
                          TaxTotal ,
                          Tax_Total ,
                          BargainTotal ,
                          [Convert] ,
                          DiscountTotal ,
                          SaleMoney ,
                          Usedtype ,
                          PHRows ,
                          Vchcode
						)
                        SELECT  b.DlyOrder ,
                                a.SizeID ,
                                a.ColorID ,
                                SUM(a.Qty) AS qty ,
                                0 ,
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) ,----total
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) ,--税额----TaxTotal 
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) , -- 含税金额 -----tax_total
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) , ---BargainTotal
                                0 ,
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) ,--DiscountTotal
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) , --SaleMoney
                                1 ,
                                b.PHRows ,
                                @VchCode
                        FROM    dbo.tpx_ReplenishList a
                                INNER JOIN bakdly b ON a.Ptypeid = b.Ptypeid
                                                       AND b.Vchcode = @VchCode
                                                       AND a.ColorID = B.ColorID
                                                       AND a.Comment = b.Comment
                                INNER JOIN dlyndx d ON b.vchcode=d.vchcode
                                LEFT JOIN Goodsstocks g ON d.ktypeid2 = g.KtypeId
                                                           AND b.PtypeId = g.PtypeId
                        WHERE   CHARINDEX(':' + a.ZBKeyId + ':', @tmpCodeStr) > 0
                        GROUP BY a.ptypeid ,
                                a.ColorID ,
                                a.SizeID ,
                                b.DlyOrder ,
                                g.price ,
                                a.Comment ,
                                b.PHRows
                IF @@ROWCOUNT <= 0 
                    GOTO error       
	            
                UPDATE  bakdly
                SET     total = b.total ,
                        TaxTotal = b.TaxTotal ,
                        Tax_Total = b.Tax_Total ,
                        BargainTotal = b.BargainTotal ,
                        [Convert] = b.[Convert] ,
                        DiscountTotal = b.DiscountTotal ,
                        SaleMoney = b.SaleMoney ,
                        price = CASE WHEN a.qty = 0 THEN 0
                                     ELSE ROUND(b.total / a.qty, @dig_price)
                                END
                FROM    bakdly a ,
                        ( SELECT    DlyOrder ,
                                    SUM(total) AS total ,
                                    SUM(TaxTotal) AS TaxTotal ,
                                    SUM(Tax_Total) AS Tax_Total ,
                                    SUM(BargainTotal) AS BargainTotal ,
                                    SUM([Convert]) AS [Convert] ,
                                    SUM(DiscountTotal) AS DiscountTotal ,
                                    SUM(SaleMoney) AS SaleMoney
                          FROM      bakdlydetail
                          GROUP BY  DlyOrder
                        ) AS b
                WHERE   a.vchcode = @VchCode
                        AND a.dlyorder = b.dlyorder 
                IF @@ROWCOUNT <= 0 
                    GOTO error  
                UPDATE  dbo.DlyNdx
                SET     qty = b.qty ,
                        total = b.total ,
                        checkdate = GETDATE() ,
                        VerifyFlow = CASE WHEN @CheckAndAccept = 0
                                               AND @vchtype = 218 THEN 0
                                          ELSE 1
                                     END ,
                        branchid2 = CASE WHEN @vchtype = 17 THEN ''
                                         ELSE branchid2
                                    END
                FROM    dlyndx a ,
                        ( SELECT    Vchcode ,
                                    SUM(qty) AS qty ,
                                    SUM(SaleMoney) AS total
                          FROM      bakdly
                          WHERE     UsedType = 1
                                    AND vchcode = @VchCode
                          GROUP BY  Vchcode
                        ) AS b
                WHERE   a.Vchcode = b.Vchcode
                        AND a.Vchcode = @VchCode
                IF @@ROWCOUNT <= 0 
                    GOTO error  
            END

        UPDATE  dbo.tpx_SaleIndex
        SET     draft = 1
        WHERE   JTypeId = @ABranchid
                AND CHARINDEX(':' + keyid + ':', @BillCode) > 0  
        GOTO sucess
    END TRY
    BEGIN CATCH
        PRINT ERROR_MESSAGE()
        GOTO Error
    END CATCH
    sucess:
    BEGIN
    --判断系统配置是否要用单据自动连续编号  
        DECLARE @orderid INT ,
            @stats INT
        SET @orderid = 13  
        SET @stats = 0  
        EXEC FZBS_FZGetSysCon @orderid, @stats OUTPUT  
        IF @stats = 1 
            BEGIN  
                --SELECT TOP 1
                --        @BillDate = SaleDate
                --FROM    dbo.tpx_SaleIndex a
                --WHERE   CHARINDEX(':' + keyid + ':', @BillCode) > 0    
                EXEC FZBS_FZModifyVchnumber @vchtype, @BillDate  
            END  
	--处理虚拟库存
        IF EXISTS ( SELECT TOP 1
                            vchcode
                    FROM    dlyndx
                    WHERE   vchcode = @VchCode ) 
            BEGIN
                DECLARE @nRetVirtual INT
                EXEC @nRetVirtual= FZModifyVirtualGoods 'BakDly', '', @VchCode,
                    1 --  smallint
                IF @nRetVirtual < 0 
                    BEGIN
                        GOTO error
                    END
		
            END
        COMMIT TRAN
        RETURN 0
    END
    Error:
    BEGIN
        ROLLBACK TRAN
        RETURN -1
    END
    Error1:
    BEGIN
        ROLLBACK TRAN
        RETURN -2
    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].[FZBS_PosToDraftBill]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZBS_PosToDraftBill]
GO
--  ********************************************************************************************
--  ||   Create ：老罗  2012-10-19  
--  ||                                                                                   
--  ||   过程名称： FZBS_PosToDraftBill                                   
--  ||   过程功能： 零售小票结转成总部相关单据草稿
--  ||
--  ||==========================================================================================
-- return -1 结存失败，单据插入失败！
-- return -2 结存失败，你选择的单据已经被其他人结存！
CREATE PROCEDURE FZBS_PosToDraftBill
    (
      @ABranchid VARCHAR(50) ,  	--机构ID
      @BillCode VARCHAR(8000) = '' , 	--单据编号
      @ConditionStr VARCHAR(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开
    )
AS 
    DECLARE @Btypeid VARCHAR(50)	--客户
    DECLARE @PosVchcode INT  
    DECLARE @Branchid VARCHAR(50)
    DECLARE @Branchid2 VARCHAR(50)    
    DECLARE @BranchType INT
    DECLARE @KtypeId VARCHAR(50)
    DECLARE @KtypeId2 VARCHAR(50)
    DECLARE @HandleManID VARCHAR(50)
    DECLARE @Etypeid VARCHAR(50)
    DECLARE @VchType INT
    DECLARE @VipCardID VARCHAR(50)
    DECLARE @PosUserCode VARCHAR(50)
    DECLARE @Dtypeid VARCHAR(50) --部门ID
    DECLARE @VchCode VARCHAR(50)
    DECLARE @DetailId INT
    DECLARE @InputName VARCHAR(50)
    DECLARE @site INT= 0
    DECLARE @tmpHandleManID VARCHAR(50)
    DECLARE @tmpetypeid VARCHAR(50)
    DECLARE @tmpType VARCHAR(1)
    DECLARE @tmpVipCardID VARCHAR(50)
    DECLARE @tmpCodeStr VARCHAR(8000)
    DECLARE @Period INT	
    
    DECLARE @CashSum NUMERIC(24, 10)
    DECLARE @BakMoneySum NUMERIC(24, 10)
    DECLARE @ReplaceCashSum NUMERIC(24, 10)
    DECLARE @CreditSum NUMERIC(24, 10)
    DECLARE @VipCardPay NUMERIC(24, 10)
    DECLARE @RetailChange NUMERIC(24, 10)
    DECLARE @RetailSum NUMERIC(24, 10)
    DECLARE @PromRtnReplaceCashSum NUMERIC(24, 10)
    DECLARE @SubValue VARCHAR(10) 
    DECLARE @BillDate VARCHAR(10)
    DECLARE @Keyid VARCHAR(50)   
    DECLARE @Tax NUMERIC(24, 10) 
    DECLARE @Number NVARCHAR(50) 
    DECLARE @Summary VARCHAR(200)= ''
    DECLARE @Comment VARCHAR(200)= ''
    DECLARE @CheckAndAccept BIT= 1
    

    SET @PosVchcode = 0
    	--单据类型
	--00000	所有单据   select * from vchtype
	--00001	零售单
	--00002	订金付入
	--00003	维修单
	--00004	补货申请单  --加盟店配货订单  发货类型为“补货  221
	--00005	退货申请单  --加盟商退货申请单，退货类型为“正常退货”
	--00006	盘点指令单
	--00007	盘点单
	--00008	调拨单      --同价调拨单
	--00009	调配单      --同价配货单，业务类型“调配”，发货类型“补货”
    SELECT TOP 1        -- 目前大部分POS单据不能实现合并成一张单据 老罗注释
            @PosVchcode = a.posvchcode ,
            @HandleManID = a.salesman ,
            @Etypeid = a.cashier ,
            @Btypeid = ISNULL(a.btypeid, '') ,
            @KtypeId = ISNULL(a.ktypeid, '') ,
            @KtypeId2 = ISNULL(a.ktypeid2, '') ,
            @VipCardID = a.VipCardId ,
            @PosUserCode = a.BillCode ,
            @BillDate = CONVERT(VARCHAR(10), CASE WHEN YEAR(a.CheckOutDate) < 2000
                                                  THEN a.saledate
                                                  WHEN vtypeid IN ( '00008',
                                                              '00009' )
                                                  THEN a.SaleDate
                                                  ELSE a.CheckOutDate
                                             END, 120) ,
            @VchType = CASE WHEN vtypeid = '00001' THEN 12
                            WHEN vtypeid = '00002' THEN 0   --暂时代替
                            WHEN vtypeid = '00003' THEN 0   --暂时代替
                            WHEN vtypeid = '00004' THEN 221
                            WHEN vtypeid = '00005' THEN 223
                            WHEN vtypeid = '00006' THEN 0   --暂时代替
                            WHEN vtypeid = '00007' THEN 0   --暂时代替
                            WHEN vtypeid = '00008' THEN 17
                            WHEN vtypeid = '00009' THEN 218
                            ELSE 0
                       END ,
            @Branchid = JTypeId ,
            @Keyid = keyid ,
            @Summary = Summary ,
            @Comment = Comment
    FROM    dbo.tpx_SaleIndex a
    WHERE   JTypeId = @ABranchid
            AND CHARINDEX(':' + Keyid + ':', @BillCode) > 0  

    SELECT TOP 1
            @Period = ISNULL(SubValue, 0)
    FROM    SysData
    WHERE   SubName = 'Period'  

    SELECT TOP 1
            @VipCardPay = COUNT(1)
    FROM    dbo.tpx_SaleVipList
    WHERE   CHARINDEX(':' + zbKeyid + ':', @BillCode) > 0  
    IF @KtypeId2 <> '' 
        SELECT TOP 1
                @Branchid2 = BranchID
        FROM    stock
        WHERE   typeid = @ktypeid
    SELECT TOP 1
            @SubValue = ISNULL(CashAsBillMoney, '0') ,
            @BranchType = BranchType ,
            @CheckAndAccept = CheckAndAccept
    FROM    dbo.Branch
    WHERE   branchid = @Branchid

    
    DECLARE @tmpName VARCHAR(100)
    DECLARE @tmpName1 VARCHAR(100)
    
    IF @HandleManID = ''
        OR @HandleManID IS NULL 
        BEGIN    
		--
            SELECT TOP 1
                    @HandleManID = b.etypeid
            FROM    dbo.tpx_SaleList a
                    INNER JOIN tpx_SaleManList b ON a.keyid = b.CBKeyId
            WHERE   ZBKeyId = @keyid
        END
    SET @tmpHandleManID = @HandleManID
    SET @tmpetypeid = @Etypeid
    SET @tmpVipCardID = @VipCardID
    SET @BakMoneySum = 0

    DECLARE @tmpPtypeid VARCHAR(100)

    SET @tmpCodeStr = @BillCode
    SELECT TOP 1
            @Dtypeid = Dtypeid
    FROM    dbo.Employee
    WHERE   TypeId = @HandleManID --取职员所属部门的ID
    
    DECLARE @dig_qty INT ,
        @dig_price INT ,
        @dig_total INT ,
        @dig_dis INT ,
        @dig_tax INT ,
        @dig_rate INT
    EXEC GetDig @dig_qty OUTPUT, @dig_price OUTPUT, @dig_total OUTPUT,
        @dig_dis OUTPUT, @dig_tax OUTPUT, @dig_rate OUTPUT


    BEGIN TRAN
    BEGIN TRY 
		--获取内部机构或加盟机构现金、银行卡、代金券对应科目及税率
        DECLARE @ACash VARCHAR(50)
        DECLARE @ACard VARCHAR(50)
        DECLARE @ATicket VARCHAR(50)
        DECLARE @TaxRate NUMERIC(24, 10)= 0.00
        IF @BranchType <> 3 
            BEGIN
                SELECT TOP 1
                        @ACash = ATypeId
                FROM    dbo.tpx_PosCashTypeConfig
                WHERE   Jtypeid = @ABranchid
                        AND Keyid = '00001'
                SELECT TOP 1
                        @ACard = ATypeId
                FROM    dbo.tpx_PosCashTypeConfig
                WHERE   Jtypeid = @ABranchid
                        AND Keyid = '00002'
                SELECT TOP 1
                        @ATicket = ATypeId
                FROM    dbo.tpx_PosCashTypeConfig
                WHERE   Jtypeid = @ABranchid
                        AND Keyid = '00003'
                SELECT TOP 1
                        @Tax = ROUND(Rate, @dig_tax)
                FROM    dbo.tpx_PosCashMain
                WHERE   Jtypeid = @ABranchid
					
            END
        IF @Summary = '' 
            SET @tmpName1 = '前台POS小票【' + @PosUserCode + '】'
        ELSE 
            SET @tmpName1 = @Summary
	    
        IF @ConditionStr = 'ht' 
            SET @tmpName1 = @tmpName1 + '，后台结存生成！'
	    
        IF @PosVchcode <> 0
            AND @VchType = 12 
            BEGIN

                IF @BranchType = 1
                    OR @BranchType = 7
                    OR @BranchType = 4 
                    SET @VchType = 12	-- 零售单
	                
                IF @BranchType = 3 
                    BEGIN
                        SET @VchType = 100	-- 代销零售单
                        SET @Tax = 0--代销零售单税率默认为0，再通过以面一句脚本更新（可能BtypeDistribute此机构的信息就会使用这个默认值0）                   
                        SELECT  @Tax = bd.TaxRate
                        FROM    Branch b
                                INNER JOIN dbo.BtypeDistribute bd ON b.Branchid = @Branchid
                                                              AND bd.BtypeId = b.BtypeId
                    END
	            
	           
                SET @Tax = ISNULL(@Tax, 0)
				--得到单据Number
                EXEC FN_VchNumber_Get @VchType, @BillDate, @ABranchid,
                    '127.0.0.1', 1, @Number OUTPUT

				-- 增加一个主表
                EXEC @VchCode = FZInsertDlyNdx 2, --Billtype 
                    @BillDate, -- @date
                    @Number, -- @number
                    @VchType, -- @vchtype
                    @tmpName1, -- @summary
                    @Comment, -- @comment
                    @Btypeid, -- @Btypeid
                    @tmpHandleManID, -- @Etypeid
                    @KtypeId, -- @KtypeId
                    '', -- @KtypeId2
                    0, -- @ifcheck
                    '', -- @checke
                    '', -- @accounte              
                    @tmpetypeid, -- @inputno
                    10, -- @draft
                    @tmpVipCardId, -- @vipcardid
                    100, -- @vipdiscount
                    0, -- @bartertype
                    @Dtypeid, -- @deptid
                    @BillDate, -- @limittime
                    '', -- @inputno1
                    '', -- @inputno2
                    '', -- @inputno3
                    100, -- @zddiscount
                    0, -- @zddiscountprice
                    0, -- @preferential
                    '', --@InputNo4
                    '', --@InputNo5
                    '', --科目ID
                    0, --@AtypeTotal 
                    '', --@ExpandId
                    '', --@ZoneId
                    '', --@ZoneId2
                    @site, -- @SiteId
                    @Branchid
				IF @VchCode<0 
				BEGIN
					  ROLLBACK TRAN
					  IF @VchCode<>-1
					  	  RETURN -3
					  ELSE
						  RETURN -1
				END
				--占用account字段设置POS小票生成草稿的标志，占用backmoney字段用来记录公共POS的单据积分金额
                UPDATE  DlyNdx
                SET     account = 'COMMONPOSLSJC' ,
                        BackMoney = ( SELECT    SUM(VipIntegral) AS jfje
                                      FROM      dbo.tpx_SaleIndex a
                                      WHERE     a.JTypeId = @ABranchid
                                                AND CHARINDEX(':' + keyid
                                                              + ':', @BillCode) > 0
                                    )
                WHERE   VchCode = @VchCode
    
  
                SELECT  a.ColorID ,	         SUM(a.DisCount) DisCount ,
				        a.DisCountRate ,    a.Price ,        a.PtypeID ,		   
				        SUM(a.Qty) Qty ,	a.RetailPrice ,  a.SizeID ,	  
				        SUM( a.Total )  Total ,
				        a.UnitId 
				        INTO  #tpx_SaleList_temp   
			    FROM    dbo.tpx_SaleList a
                        WHERE   CHARINDEX(':' + a.zbkeyid + ':', @tmpCodeStr) > 0
			    GROUP BY  a.ColorID ,	   
				        a.DisCountRate ,    a.Price ,       a.PtypeID ,			      
				        a.RetailPrice ,     		        a.SizeID ,	      
				        a.UnitId 
				HAVING  SUM(a.Qty)<>0 AND SUM( a.Total )<>0       
                     
                INSERT  INTO [dbo].[bakdly]
                        ( [vchcode] ,
                          [atypeId] ,
                          [btypeId] ,
                          [etypeId] ,
                          [ktypeId] ,
                          [branchid] ,
                          vipcardid ,
                          billtype ,
                          RetailPrice ,
                          [PtypeId] ,
                          [Qty] ,
                          [discount] ,
                          [discountprice] ,
                          [costtotal] ,
                          [costPrice] ,
                          [price] ,
                          [total] ,
                          [TaxPrice] ,
                          [TaxTotal] ,
                          [comment] ,
                          [date] ,
                          [usedtype] ,
                          [period] ,
                          [tax_total] ,
                          [tax] ,
                          [discounttotal] ,
                          [costmode] ,
                          [vchtype] ,
                          [Dtypeid] ,
                          [colorid] ,
                          [VipDiscount] ,
                          [convert] ,
                          [roworder] ,
                          [bargainTotal] ,
                          [ifSupply] ,
                          [SaleMoney] ,
                          [MarketDiscount] ,
                          [MarketDiscount1] ,
                          [salemode] ,
                          [PHRows]
						)
                        SELECT  @VchCode ,
                                '0000100001' ,
                                @Btypeid ,
                                @tmpHandleManID ,
                                @KtypeId ,
                                @Branchid ,
                                @tmpVipCardId ,
                                2 ,
                                RetailPrice ,
                                Ptypeid ,
                                SUM(Qty) ,
                                100 ,
                                RetailPrice ,
                                0 ,
                                0 ,
                                RetailPrice ,
                                0 ,----total
                                CASE @BranchType
                                  WHEN 3
                                  THEN ROUND(ISNULL(SUM(a.Total), 0) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100
                                             / ( CASE WHEN SUM(Qty) = 0 THEN 1
                                                      ELSE SUM(qty)
                                                 END ), @dig_price)
                                  ELSE ROUND(ISNULL(SUM(a.Total), 0)
                                             / ( CASE WHEN SUM(Qty) = 0 THEN 1
                                                      ELSE SUM(qty)
                                                 END ), @dig_price)                --税价
                                END ,
                                0 ,--税额----TaxTotal 
                                '' ,
                                @BillDate ,
                                1 ,
                                @Period ,
                                CASE @BranchType
                                  WHEN 3
                                  THEN ROUND(SUM(ISNULL(a.Total, 0)) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100,
                                             @dig_total)
                                  ELSE ROUND(SUM(ISNULL(a.Total, 0)),
                                             @dig_total)	       -- 含税金额 -----POS 那边的Total 是含税的 tax_total
                                END ,
                                ISNULL(@Tax, 0.00) ,
                                price ,  -- discounttotal 本来这里该直接写0 此处暂借用来写折后价，
										 --	是为了Group by ,不然插bakdlydetail时就要失去关联
										 -- 在后面要更正的
                                0 ,
                                @VchType ,
                                '' ,--dtypeid
                                ColorID ,
                                100 ,--vipdiscount
                                0 ,--convert
                                0 ,
                                0 ,-- 成交金额 扣税-----bargainTotal
                                0 ,
                                0 , ------Salemoney
                                CASE @BranchType
                                  WHEN 3
                                  THEN ISNULL(( SELECT  b.Price
                                                FROM    ptypeprice b
                                                WHERE   b.ptypeId = a.ptypeid
                                                        AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                              ), 0)
                                  ELSE 0
                                END ,
                                CASE @BranchType
                                  WHEN 3
                                  THEN ISNULL(( SELECT  b.Price
                                                FROM    ptypeprice b
                                                WHERE   b.ptypeId = a.ptypeid
                                                        AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                              ), 0)
                                  ELSE 0
                                END ,
                                0 ,
                                ROW_NUMBER() OVER ( ORDER BY ColorID ) --获得行号，对应PHrows字段
                        FROM   #tpx_SaleList_temp a
                        GROUP BY Ptypeid ,
                                RetailPrice ,
                                price ,
                                ColorID ,
                                SIGN(QTY)
                --写三级明细                
            	-----*******************************************测试用    
                --SELECT *FROM bakdly WHERE vchcode=@VchCode
                --SELECT  b.DlyOrder ,
                --                a.SizeID ,
                --                a.ColorID ,
                --                SUM(a.Qty) AS qty ,
                --                0 ,
                --                ROUND(CAST(CAST(SUM(a.Qty) AS NUMERIC(24,10)) * a.RetailPrice AS NUMERIC(24,10)), @dig_total) ,----total
                --                CASE @BranchType
                --                  WHEN 3
                --                  THEN ROUND(CAST(Cast(SUM(a.Total) AS NUMERIC(24,10)) * ( 100
                --                                              - ISNULL(( SELECT
                --                                              b.Price
                --                                              FROM
                --                                              ptypeprice b
                --                                              WHERE
                --                                              b.ptypeId = a.ptypeid
                --                                              AND b.PriceTypeId = ( SELECT
                --                                              c.MarketDiscountID
                --                                              FROM
                --                                              btypedistribute c
                --                                              WHERE
                --                                              c.btypeid = @Btypeid
                --                                              )
                --                                              ), 0) ) / 100 AS NUMERIC(24,10)),
                --                             @dig_total)
                --                       - ROUND(CAST(Cast(SUM(a.Total) AS NUMERIC(24,10) ) * ( 100
                --                                              - ISNULL(( SELECT
                --                                              b.Price
                --                                              FROM
                --                                              ptypeprice b
                --                                              WHERE
                --                                              b.ptypeId = a.ptypeid
                --                                              AND b.PriceTypeId = ( SELECT
                --                                              c.MarketDiscountID
                --                                              FROM
                --                                              btypedistribute c
                --                                              WHERE
                --                                              c.btypeid = @Btypeid
                --                                              )
                --                                              ), 0) ) / 100
                --                               / ( 1 + ISNULL(@Tax, 0) / 100 ) AS NUMERIC(24,10)),
                --                               @dig_total)
                --                  ELSE ROUND(cast(SUM(a.Total) AS NUMERIC(24,10)),
                --                             @dig_total)
                --                       - ROUND(CAST(Cast(SUM(a.Total) AS NUMERIC(24,10) ) / ( 1
                --                                              + @TaxRate / 100 ) AS NUMERIC(24,10)),
                --                               @dig_total)
                --                END ,  --税额----TaxTotal 
                --                CASE @BranchType
                --                  WHEN 3
                --                  THEN ROUND(CAST(Cast(SUM(a.Total) AS NUMERIC(24,10) ) * ( 100
                --                                              - ISNULL(( SELECT
                --                                              b.Price
                --                                              FROM
                --                                              ptypeprice b
                --                                              WHERE
                --                                              b.ptypeId = a.ptypeid
                --                                              AND b.PriceTypeId = ( SELECT
                --                                              c.MarketDiscountID
                --                                              FROM
                --                                              btypedistribute c
                --                                              WHERE
                --                                              c.btypeid = @Btypeid
                --                                              )
                --                                              ), 0) ) / 100 AS NUMERIC(24,10)),
                --                             @dig_total)
                --                  ELSE ROUND(ISNULL(SUM(a.Total), 0),
                --                             @dig_total)
                --                END ,-- 含税金额 -----tax_total
                --                CASE @BranchType
                --                  WHEN 3
                --                  THEN ROUND(CAST(Cast(SUM(a.Total) as numeric(24,10)) * ( 100
                --                                              - ISNULL(( SELECT
                --                                              b.Price
                --                                              FROM
                --                                              ptypeprice b
                --                                              WHERE
                --                                              b.ptypeId = a.ptypeid
                --                                              AND b.PriceTypeId = ( SELECT
                --                                              c.MarketDiscountID
                --                                              FROM
                --                                              btypedistribute c
                --                                              WHERE
                --                                              c.btypeid = @Btypeid
                --                                              )
                --                                              ), 0) ) / 100
                --                             / ( 1 + @Tax / 100 ) AS NUMERIC(24,10)), @dig_total)
                --                  ELSE ROUND(Cast(Cast(SUM(a.Total) AS NUMERIC(24,10)) / ( 1
                --                                              + @TaxRate / 100 ) AS NUMERIC(24,10)),
                --                             @dig_total)
                --                END ,---BargainTotal =含税金额/(1+税率/100)
                --                CASE @BranchType
                --                  WHEN 3
                --                  THEN ----
                --                       ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24,10)) *a.RetailPrice AS NUMERIC(24,10)),
                --                             @dig_total) - ISNULL(SUM(a.Total),
                --                                              0)
                --                  ELSE ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24,10)) *a.RetailPrice AS NUMERIC(24,10)),
                --                             @dig_total)
                --                       - ROUND(Cast(Cast(SUM(a.Total) AS NUMERIC(24,10)) / ( 1
                --                                              + @Tax / 100 ) AS NUMERIC(24,10)),
                --                               @dig_total)
                --                END ,--convert
                --                ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24,10)) *a.RetailPrice AS NUMERIC(24,10)), @dig_total) ,--DiscountTotal
                --                ISNULL(SUM(a.Total), 0) , --salemoney
                --                1 ,
                --                b.PHRows ,
                --                @VchCode
                --        FROM    dbo.tpx_SaleList a
                --                INNER JOIN bakdly b ON a.Ptypeid = b.Ptypeid
                --                                       AND a.RetailPrice = b.Price
                --                                       AND a.ColorID = B.ColorID
                --                                       AND a.price = b.discounttotal
                --                                       AND b.Vchcode = @VchCode
                --                                       --AND SIGN(SUM(a.QTY))=SIGN(b.qty)
                --        WHERE   CHARINDEX(':' + a.ZBKeyId + ':', @tmpCodeStr) > 0
                --        GROUP BY a.ptypeid ,
                --                a.ColorID ,
                --                a.SizeID ,
                --                b.DlyOrder ,
                --                a.RetailPrice ,
                --                a.price,
                --                SIGN(a.qty),
                --                b.qty, 
                --                b.PHRows     
                --        HAVING  SIGN(SUM(a.QTY))=SIGN(b.qty)          
                ----*******************************************测试用
                INSERT  INTO bakDlydetail
                        ( dlyorder ,
                          sizeid ,
                          colorid ,
                          Qty ,
                          CostTotal ,
                          Total ,
                          TaxTotal ,
                          Tax_Total ,
                          BargainTotal ,
                          [Convert] ,
                          DiscountTotal ,
                          SaleMoney ,
                          Usedtype ,
                          PHRows ,
                          Vchcode
						)
                        SELECT  b.DlyOrder ,
                                a.SizeID ,
                                a.ColorID ,
                                SUM(a.Qty) AS qty ,
                                0 ,
                                ROUND(CAST(CAST(SUM(a.Qty) AS NUMERIC(24, 10))
                                      * a.RetailPrice AS NUMERIC(24, 10)),
                                      @dig_total) ,----total
                                CASE @BranchType
                                  WHEN 3
                                  THEN ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100 AS NUMERIC(24,
                                                              10)), @dig_total)
                                       - ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100
                                               / ( 1 + ISNULL(@Tax, 0) / 100 ) AS NUMERIC(24,
                                                              10)), @dig_total)
                                  ELSE ROUND(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)), @dig_total)
                                       - ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) / ( 1
                                                              + @Tax / 100 ) AS NUMERIC(24,
                                                              10)), @dig_total)
                                END ,  --税额----TaxTotal 
                                CASE @BranchType
                                  WHEN 3
                                  THEN ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100 AS NUMERIC(24,
                                                              10)), @dig_total)
                                  ELSE ROUND(ISNULL(SUM(a.Total), 0),
                                             @dig_total)
                                END ,-- 含税金额 -----tax_total
                                CASE @BranchType
                                  WHEN 3
                                  THEN ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100
                                             / ( 1 + @Tax / 100 ) AS NUMERIC(24,
                                                              10)), @dig_total)
                                  ELSE ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) / ( 1
                                                              + @Tax / 100 ) AS NUMERIC(24,
                                                              10)), @dig_total)
                                END ,---BargainTotal =含税金额/(1+税率/100)
                                CASE @BranchType
                                  WHEN 3
                                  THEN ----
                                       ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24,
                                                              10))
                                             * a.RetailPrice AS NUMERIC(24, 10)),
                                             @dig_total) - ISNULL(SUM(a.Total),
                                                              0)
                                  ELSE ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24,
                                                              10))
                                             * a.RetailPrice AS NUMERIC(24, 10)),
                                             @dig_total)
                                       - ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) / ( 1
                                                              + @Tax / 100 ) AS NUMERIC(24,
                                                              10)), @dig_total)
                                END ,--convert
                                ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24, 10))
                                      * a.RetailPrice AS NUMERIC(24, 10)),
                                      @dig_total) ,--DiscountTotal
                                ISNULL(ROUND(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)), @dig_total),
                                       0) , --salemoney
                                1 ,
                                b.PHRows ,
                                @VchCode
                        FROM    #tpx_SaleList_temp a
                                INNER JOIN bakdly b ON a.Ptypeid = b.Ptypeid
                                                       AND a.RetailPrice = b.Price
                                                       AND a.ColorID = B.ColorID
                                                       AND a.price = b.discounttotal
                                                       AND b.Vchcode = @VchCode
                                                       --AND SIGN(SUM(a.QTY))=SIGN(b.qty)
                        GROUP BY a.ptypeid ,
                                a.ColorID ,
                                a.SizeID ,
                                b.DlyOrder ,
                                a.RetailPrice ,
                                a.price ,
                                SIGN(a.qty) ,
                                b.qty ,
                                b.PHRows
                        HAVING  SIGN(SUM(a.QTY)) = SIGN(b.qty)          
                       
	                             
                IF EXISTS ( SELECT  1            --POS小票类单据生成总部草稿以后，更改POS小票类单据的状态
                            FROM    dbo.tpx_SaleIndex
                            WHERE   draftvchCode > 0
                                    AND CHARINDEX(':' + keyid + ':',
                                                  @tmpCodeStr) > 0 ) 
                    GOTO error1  
                ELSE 
                    UPDATE  dbo.tpx_SaleIndex
                    SET     draftvchCode = @VchCode
                    WHERE   Jtypeid = @ABranchid
                            AND CHARINDEX(':' + keyid + ':', @tmpCodeStr) > 0      
				--此处收款科目是动态的，根据用户设置可能有很多种以前的老代码删除了 modify by 老罗 2012-11-12
 
				-- 写收款科目

                IF ( @VchType = 12
                     OR @VchType = 13
                   )
                    AND @RetailSum <> 0
                    AND @SubValue = '1' 
                    UPDATE  dbo.DlyNdx
                    SET     AtypeTotal = ISNULL(@RetailSum, 0)
                    WHERE   VchCode = @VchCode
			   -- modify by 老罗 2012-11-12 因为是动态的科目，所以直接取pos的付款方式表tpx_salepaylist中记录
	   
                IF @BranchType <> 3 
                    BEGIN
                        IF EXISTS ( SELECT  1
                                    FROM    dbo.tpx_SalePayList
                                    WHERE   CHARINDEX(':' + ZBkeyid + ':',
                                                      @tmpCodeStr) > 0 ) 
                            BEGIN
                                INSERT  INTO [dbo].[bakdly]
                                        ( [vchcode] ,
                                          [atypeId] ,
                                          [btypeId] ,
                                          [etypeId] ,
                                          [ktypeId] ,
                                          [PtypeId] ,
                                          [branchid] ,
                                          [billtype ] ,
                                          [Qty] ,
                                          [discount] ,
                                          [discountprice] ,
                                          [costtotal] ,
                                          [costPrice] ,
                                          [price] ,
                                          [total] ,
                                          [TaxPrice] ,
                                          [TaxTotal] ,
                                          [comment] ,
                                          [date] ,
                                          [usedtype] ,
                                          [period] ,
                                          [tax_total] ,
                                          [tax] ,
                                          [discounttotal] ,
                                          [costmode] ,
                                          [vchtype] ,
                                          [unit] ,
                                          [Dtypeid] ,
                                          [colorid] ,
                                          [VipDiscount] ,
                                          [convert] ,
                                          [roworder] ,
                                          [bargainTotal] ,
                                          [ifSupply]
									    )
                                        SELECT  @VchCode ,
                                                p.AtypeId ,
                                                @Btypeid ,
                                                @tmpetypeid ,
                                                @KtypeId ,
                                                '' ,
                                                @branchid ,
                                                2 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                SUM(Total) ,
                                                0 ,
                                                0 ,
                                                CASE WHEN p.Keyid='00003' THEN 'systemDJQ' ELSE '' END,
                                                @BillDate ,
                                                '2' ,
                                                @Period ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                @VchType ,
                                                0 ,
                                                '' ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0
                                        FROM    dbo.tpx_SalePayList s
                                                INNER JOIN dbo.tpx_PosCashTypeConfig p ON s.akeyid = p.keyid
                                                              AND p.Jtypeid = @Branchid
                                        WHERE   CHARINDEX(':' + s.ZBkeyid
                                                          + ':', @tmpCodeStr) > 0
                                                AND s.AKeyId <> '00004'
                                        GROUP BY p.AtypeId ,p.Keyid                   
                                
                            END 
                        IF ABS(@vipcardpay) > 0 
                            BEGIN
                                INSERT  INTO [dbo].[bakdly]
                                        ( [vchcode] ,
                                          [atypeId] ,
                                          [btypeId] ,
                                          [etypeId] ,
                                          [ktypeId] ,
                                          [PtypeId] ,
                                          [branchid] ,
                                          vipcardid ,
                                          billtype ,
                                          [Qty] ,
                                          [discount] ,
                                          [discountprice] ,
                                          [costtotal] ,
                                          [costPrice] ,
                                          [price] ,
                                          [total] ,
                                          [TaxPrice] ,
                                          [TaxTotal] ,
                                          [comment] ,
                                          [date] ,
                                          [usedtype] ,
                                          [period] ,
                                          [tax_total] ,
                                          [tax] ,
                                          [discounttotal] ,
                                          [costmode] ,
                                          [vchtype] ,
                                          [unit] ,
                                          [Dtypeid] ,
                                          [colorid] ,
                                          [VipDiscount] ,
                                          [convert] ,
                                          [roworder] ,
                                          [bargainTotal] ,
                                          [ifSupply]
										)
                                        SELECT  @VchCode ,
                                                '0000299999' ,
                                                @Btypeid ,
                                                @tmpetypeid ,
                                                @KtypeId ,
                                                '' ,
                                                @branchid ,
                                                vipid ,
                                                2 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                CASE WHEN SIGN(c.FinallyTotal) >= 0
                                                     THEN a.Total
                                                     ELSE -1 * a.Total
                                                END ,
                                                0 ,
                                                0 ,
                                                '卡号:' + cardno + ' 持卡人:'
                                                + holderName ,
                                                @BillDate ,
                                                '2' ,
                                                @Period ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                @VchType ,
                                                0 ,
                                                '' ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0
                                        FROM    dbo.tpx_SaleVipList a
                                                INNER JOIN dbo.tpx_SaleIndex c ON a.ZBKeyId = c.keyId
                                                LEFT JOIN vipcards b ON a.vipid = b.cardid
                                        WHERE   CHARINDEX(':' + a.ZBKeyId
                                                          + ':', @tmpCodeStr) > 0 
                              
                            END
                    END
				
                       
	                   
                UPDATE  bakdly
                SET     total = b.total ,
                        TaxTotal = b.TaxTotal ,
                        Tax_Total = b.Tax_Total ,
                        BargainTotal = b.BargainTotal ,
                        [Convert] = b.[Convert] ,
                        DiscountTotal = b.DiscountTotal ,
                        SaleMoney = b.SaleMoney
                FROM    bakdly a ,
                        ( SELECT    DlyOrder ,
                                    ROUND(CAST(SUM(total) AS NUMERIC(24, 10)),
                                          @dig_total) AS total ,
                                    ROUND(CAST(SUM(TaxTotal) AS NUMERIC(24, 10)),
                                          @dig_Total) AS TaxTotal ,
                                    ROUND(CAST(SUM(Tax_Total) AS NUMERIC(24,
                                                              10)), @dig_total) AS Tax_Total ,
                                    ROUND(CAST(SUM(BargainTotal) AS NUMERIC(24,
                                                              10)), @dig_total) AS BargainTotal ,
                                    ROUND(CAST(SUM([Convert]) AS NUMERIC(24,
                                                              10)), @dig_total) AS [Convert] ,
                                    ROUND(CAST(SUM(DiscountTotal) AS NUMERIC(24,
                                                              10)), @dig_total) AS DiscountTotal ,
                                    ROUND(CAST(SUM(SaleMoney) AS NUMERIC(24,
                                                              10)), @dig_total) AS SaleMoney
                          FROM      bakdlydetail
                          WHERE     vchcode = @VchCode
                          GROUP BY  DlyOrder
                        ) AS b
                WHERE   a.vchcode = @VchCode
                        AND a.dlyorder = b.dlyorder 
	            
                UPDATE  a
                SET     a.phrows = b.phrows
                FROM    bakdlydetail a
                        INNER JOIN bakdly b ON a.vchcode = b.vchcode
                                               AND a.DlyOrder = b.DlyOrder
                WHERE   a.vchcode = @VchCode
	            
                UPDATE  dbo.DlyNdx
                SET     qty = ROUND(ISNULL(b.qty, 0.00), @dig_qty) ,
                        total = ROUND(ISNULL(b.total, 0.00), @dig_total)
                FROM    dlyndx a ,
                        ( SELECT    Vchcode ,
                                    CAST(SUM(qty) AS NUMERIC(24, 10)) AS qty ,
                                    CAST(SUM(SaleMoney) AS NUMERIC(24, 10)) AS total
                          FROM      bakdly
                          WHERE     UsedType = 1
                                    AND vchcode = @VchCode
                          GROUP BY  Vchcode
                        ) AS b
                WHERE   a.Vchcode = b.Vchcode
                        AND a.Vchcode = @VchCode
     --           --特殊处理只在结算时录入vip卡的情况（取结算第一张卡的卡号作为主表的vip卡） 此处pos端处理了
     --           IF exists(SELECT 1 FROM bakdly a INNER JOIN dlyndx d ON a.vchcode=d.vchcode 
					--	  WHERE a.VipCardID<>0 AND d.VipCardID=0 AND d.vchcode=@VchCode)
			  --  BEGIN
					--UPDATE a SET a.vipcardid=b.vipcardid FROM dlyndx a INNER JOIN 
					--	(select TOP 1 VipCardID,vchcode FROM bakdly WHERE VipCardID<>0 AND vchcode=@VchCode) b 
					--		ON a.vchcode=b.vchcode
					--WHERE b.VipCardID<>0 AND a.VipCardID=0 AND a.vchcode=@VchCode
			  --  END
                      
                --特殊处理代金卷的问题 (零售单一定会收款)
                
                IF EXISTS ( SELECT TOP 1
                                    1
                            FROM    bakdly
                            WHERE   Vchcode = @VchCode
                                    AND Comment = 'systemDJQ' ) 
                    BEGIN
                        IF EXISTS ( SELECT  SUM(Total)
                                    FROM    ( SELECT    SUM(CASE
                                                              WHEN ( NOT ptypeid IS NULL
                                                              AND ptypeid <> ''
                                                              )
                                                              THEN -salemoney
                                                              ELSE Total
                                                            END) AS Total ,
                                                        ptypeid ,
                                                        SUM(qty) qty
                                              FROM      bakdly
                                              WHERE     Vchcode = @VchCode
                                              GROUP BY  ptypeid
                                            ) c
                                    HAVING  SUM(Total) > 0
                                            AND SUM(qty) >= 0 ) 
                            BEGIN
                                UPDATE  a
                                SET     a.Total = a.Total - b.Total
                                FROM    bakdly a ,
                                        ( SELECT    SUM(Total) Total ,
                                                    vchcode
                                          FROM      ( SELECT  SUM(CASE
                                                              WHEN ( NOT ptypeid IS NULL
                                                              AND ptypeid <> ''
                                                              )
                                                              THEN -salemoney
                                                              ELSE Total
                                                              END) AS Total ,
                                                              ptypeid ,
                                                              Vchcode ,
                                                              SUM(qty) qty
                                                      FROM    bakdly
                                                      WHERE   Vchcode = @VchCode
                                                      GROUP BY ptypeid ,
                                                              vchcode
                                                    ) c
                                          GROUP BY  vchcode
                                          HAVING    SUM(Total) > 0
                                                    AND SUM(qty) >= 0
                                        ) b
                                WHERE   a.Vchcode = @VchCode
                                        AND a.Vchcode = b.vchcode
                                        AND a.Comment = 'systemDJQ'
                            END    
                        IF EXISTS ( SELECT  SUM(Total)
                                    FROM    ( SELECT    SUM(CASE
                                                              WHEN ( NOT ptypeid IS NULL
                                                              AND ptypeid <> ''
                                                              )
                                                              THEN -salemoney
                                                              ELSE Total
                                                            END) AS Total ,
                                                        ptypeid ,
                                                        SUM(qty) AS qty
                                              FROM      bakdly
                                              WHERE     Vchcode = @VchCode
                                              GROUP BY  ptypeid
                                            ) c
                                    HAVING  SUM(Total) < 0
                                            AND SUM(qty) <= 0 ) 
                            BEGIN
                                UPDATE  a
                                SET     a.Total = a.Total - b.Total
                                FROM    bakdly a ,
                                        ( SELECT    SUM(Total) Total ,
                                                    vchcode
                                          FROM      ( SELECT  SUM(CASE
                                                              WHEN ( NOT ptypeid IS NULL
                                                              AND ptypeid <> ''
                                                              )
                                                              THEN -salemoney
                                                              ELSE Total
                                                              END) AS Total ,
                                                              ptypeid ,
                                                              vchcode ,
                                                              SUM(qty) qty
                                                      FROM    bakdly
                                                      WHERE   Vchcode = @VchCode
                                                      GROUP BY ptypeid ,
                                                              vchcode
                                                    ) c
                                          GROUP BY  vchcode
                                          HAVING    SUM(Total) < 0
                                                    AND SUM(qty) <= 0
                                        ) b
                                WHERE   a.Vchcode = @VchCode
                                        AND a.Vchcode = b.vchcode
                                        AND a.Comment = 'systemDJQ'
                            END    
                    END
            END
		-- 新增一个调拨或配送单草稿
	    
        IF @PosVchcode <> 0
            AND @VchType IN ( 17, 218 ) 
            BEGIN
		
			 --得到单据Number
				
                EXEC FN_VchNumber_Get @VchType, @BillDate, @ABranchid,
                    '127.0.0.1', 1, @Number OUTPUT

				--判断是否启用配送验收流程 配送单过账的时候要判断此处不用了2012-10-29
				--DECLARE @VerifyFlow BIT
				--SELECT TOP 1 @VerifyFlow=CheckAndAccept FROM dbo.Branch WHERE BranchID=@Branchid2
				-- 增加一个主表
                EXEC @VchCode = FZInsertDlyNdx 3, --Billtype 
                    @BillDate, -- @date
                    @Number, -- @number
                    @VchType, -- @vchtype
                    @tmpName1, -- @summary
                    @comment, -- @comment
                    @Btypeid, -- @Btypeid
                    @tmpHandleManID, -- @Etypeid
                    @KtypeId, -- @KtypeId
                    @Ktypeid2, -- @KtypeId2
                    0, -- @ifcheck
                    '', -- @checke
                    'COMMONPOSLSJC', -- @accounte              
                    @tmpetypeid, -- @inputno
                    10, -- @draft
                    @tmpVipCardId, -- @vipcardid
                    100, -- @vipdiscount
                    0, -- @bartertype
                    @Dtypeid, -- @deptid
                    '', -- @limittime
                    @tmpetypeid, -- @inputno1
                    '', -- @inputno2
                    '', -- @inputno3
                    0, -- @zddiscount
                    0, -- @zddiscountprice
                    0, -- @preferential
                    '', --@InputNo4
                    '', --@InputNo5
                    '', --科目ID
                    0, --@AtypeTotal 
                    '', --@ExpandId
                    '', --@ZoneId
                    '', --@ZoneId2
                    @site, -- @SiteId
                    @Branchid2, 0, --@Total
                    '', --@Xw_Vsf1   
                    '', --@Xw_Vsf2
                    '', --@Xw_Vsf3
                    '', --@Xw_Vsf4
                    '', --@Xw_Vsf5
                    '', --@VchOrderList
                    @BranchId, --@BranchId2
                    3   --@phid
                IF @VchCode<0 
				BEGIN
					  ROLLBACK TRAN
					  IF @VchCode<>-1
					  	  RETURN -3
					  ELSE
						  RETURN -1
				END
                INSERT  INTO [dbo].[bakdly]
                        ( [vchcode] ,
                          [atypeId] ,
                          [btypeId] ,
                          [etypeId] ,
                          [ktypeId] ,
                          [branchid] ,
                          vipcardid ,
                          billtype ,
                          RetailPrice ,
                          [PtypeId] ,
                          [Qty] ,
                          [discount] ,
                          [discountprice] ,
                          [costtotal] ,
                          [costPrice] ,
                          [price] ,
                          [total] ,
                          [TaxPrice] ,
                          [TaxTotal] ,
                          [comment] ,
                          [date] ,
                          [usedtype] ,
                          [period] ,
                          [tax_total] ,
                          [tax] ,
                          [discounttotal] ,
                          [costmode] ,
                          [vchtype] ,
                          [Dtypeid] ,
                          [colorid] ,
                          [VipDiscount] ,
                          [convert] ,
                          [roworder] ,
                          [bargainTotal] ,
                          [ifSupply] ,
                          [SaleMoney] ,
                          [MarketDiscount] ,
                          [MarketDiscount1] ,
                          [salemode] ,
                          [PHRows] ,
                          OpID ,
                          Unit
		                
						)
						--Total,tax_total,bargaintotal,DiscountTotal,salemoney这五种金额直接写当前库存成本价，没有取到则写0
						--二级主表除零售金额和单价以外都写0，写完三级明细后反写二级明细
                        SELECT  @VchCode ,
                                '0000100001' ,
                                @Btypeid ,
                                @tmpHandleManID ,
                                @KtypeId ,
                                @Branchid2 ,
                                @tmpVipCardId ,
                                3 ,
                                RetailPrice ,
                                Ptypeid ,
                                SUM(Qty) ,
                                100 ,          --discount
                                0 ,            --discountprice   
                                0 ,            --costTotal
                                0 ,            --Costprice
                                0 ,            --price
                                0 ,            --total
                                0 ,            --Taxprice
                                0 ,            --TaxTotal 税额---- 
                                a.Comment ,
                                @BillDate ,
                                1 ,            --usedtype
                                @Period ,            --[period]
                                0 ,              --tax_total  含税金额 ---
                                ISNULL(@Tax, 0) ,--Tax
                                0 ,          -- discounttotal 
                                0 ,              --Costmode
                                @VchType ,
                                @dtypeid ,       --Dtypeid
                                ColorID ,
                                100 ,            --vipdiscount
                                0 ,              --convert
                                0 ,              --roworder
                                0 ,              --bargainTotal 成交金额 扣税-----
                                0 ,              --ifSupply
                                0 ,              --Salemoney
                                100 ,            --MarketDiscount  配送和调拨不用考虑商场扣率问题
                                100 ,            --MarketDiscount1
                                0 ,
                                ROW_NUMBER() OVER ( ORDER BY ColorID ) , --获得行号，对应PHrows字段
                                3 ,
                                a.Unitid
                        FROM    dbo.tpx_ReplenishList a
                        WHERE   CHARINDEX(':' + a.zbkeyid + ':', @tmpCodeStr) > 0
                        GROUP BY Ptypeid ,
                                RetailPrice ,
                                ColorID ,
                                a.Unitid ,
                                a.Comment
	                             
                IF EXISTS ( SELECT  1
                            FROM    dbo.tpx_SaleIndex
                            WHERE   draftvchCode > 0
                                    AND CHARINDEX(':' + keyid + ':',
                                                  @tmpCodeStr) > 0 ) 
                    GOTO error1  
                ELSE 
                    UPDATE  dbo.tpx_SaleIndex
                    SET     draftvchCode = @VchCode
                    WHERE   Jtypeid = @ABranchid
                            AND CHARINDEX(':' + keyid + ':', @tmpCodeStr) > 0      
	-----*******************************************测试用			
				--SELECT *FROM bakdly WHERE Vchcode=@VchCode
				--SELECT  b.DlyOrder ,
    --                            a.SizeID ,
    --                            a.ColorID ,
    --                            SUM(a.Qty) AS qty ,
    --                            0 ,
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) ,----total
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) ,--税额----TaxTotal 
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) , -- 含税金额 -----tax_total
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) , ---BargainTotal
    --                            0 ,
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) ,--DiscountTotal
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) , --SaleMoney
    --                            1 ,
    --                            b.PHRows ,
    --                            @VchCode
    --                    FROM    dbo.tpx_ReplenishList a
    --                            INNER JOIN bakdly b ON a.Ptypeid = b.Ptypeid
    --                                                   AND b.Vchcode = @VchCode
    --                                                   AND a.ColorID = B.ColorID
    --                                                   AND a.Comment=b.Comment
    --                            LEFT JOIN Goodsstocks g ON b.ktypeid = g.KtypeId
    --                                                       AND b.PtypeId = g.PtypeId
    --                    WHERE   CHARINDEX(':' + a.ZBKeyId + ':', @tmpCodeStr) > 0
    --                    GROUP BY a.ptypeid ,
    --                            a.ColorID ,
    --                            a.SizeID ,
    --                            b.DlyOrder ,
    --                            g.price ,
    --                            a.Comment,
    --                            b.PHRows
    -----*******************************************测试用
                INSERT  INTO bakDlydetail
                        ( dlyorder ,
                          sizeid ,
                          colorid ,
                          Qty ,
                          CostTotal ,
                          Total ,
                          TaxTotal ,
                          Tax_Total ,
                          BargainTotal ,
                          [Convert] ,
                          DiscountTotal ,
                          SaleMoney ,
                          Usedtype ,
                          PHRows ,
                          Vchcode
						)
                        SELECT  b.DlyOrder ,
                                a.SizeID ,
                                a.ColorID ,
                                SUM(a.Qty) AS qty ,
                                0 ,
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) ,----total
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) ,--税额----TaxTotal 
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) , -- 含税金额 -----tax_total
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) , ---BargainTotal
                                0 ,
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) ,--DiscountTotal
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) , --SaleMoney
                                1 ,
                                b.PHRows ,
                                @VchCode
                        FROM    dbo.tpx_ReplenishList a
                                INNER JOIN bakdly b ON a.Ptypeid = b.Ptypeid
                                                       AND b.Vchcode = @VchCode
                                                       AND a.ColorID = B.ColorID
                                                       AND a.Comment = b.Comment
                                INNER JOIN dlyndx d ON b.vchcode=d.vchcode
                                LEFT JOIN Goodsstocks g ON d.ktypeid2 = g.KtypeId
                                                           AND b.PtypeId = g.PtypeId
                        WHERE   CHARINDEX(':' + a.ZBKeyId + ':', @tmpCodeStr) > 0
                        GROUP BY a.ptypeid ,
                                a.ColorID ,
                                a.SizeID ,
                                b.DlyOrder ,
                                g.price ,
                                a.Comment ,
                                b.PHRows
                IF @@ROWCOUNT <= 0 
                    GOTO error       
	            
                UPDATE  bakdly
                SET     total = b.total ,
                        TaxTotal = b.TaxTotal ,
                        Tax_Total = b.Tax_Total ,
                        BargainTotal = b.BargainTotal ,
                        [Convert] = b.[Convert] ,
                        DiscountTotal = b.DiscountTotal ,
                        SaleMoney = b.SaleMoney ,
                        price = CASE WHEN a.qty = 0 THEN 0
                                     ELSE ROUND(b.total / a.qty, @dig_price)
                                END
                FROM    bakdly a ,
                        ( SELECT    DlyOrder ,
                                    SUM(total) AS total ,
                                    SUM(TaxTotal) AS TaxTotal ,
                                    SUM(Tax_Total) AS Tax_Total ,
                                    SUM(BargainTotal) AS BargainTotal ,
                                    SUM([Convert]) AS [Convert] ,
                                    SUM(DiscountTotal) AS DiscountTotal ,
                                    SUM(SaleMoney) AS SaleMoney
                          FROM      bakdlydetail
                          GROUP BY  DlyOrder
                        ) AS b
                WHERE   a.vchcode = @VchCode
                        AND a.dlyorder = b.dlyorder 
                IF @@ROWCOUNT <= 0 
                    GOTO error  
                UPDATE  dbo.DlyNdx
                SET     qty = b.qty ,
                        total = b.total ,
                        checkdate = GETDATE() ,
                        VerifyFlow = CASE WHEN @CheckAndAccept = 0
                                               AND @vchtype = 218 THEN 0
                                          ELSE 1
                                     END ,
                        branchid2 = CASE WHEN @vchtype = 17 THEN ''
                                         ELSE branchid2
                                    END
                FROM    dlyndx a ,
                        ( SELECT    Vchcode ,
                                    SUM(qty) AS qty ,
                                    SUM(SaleMoney) AS total
                          FROM      bakdly
                          WHERE     UsedType = 1
                                    AND vchcode = @VchCode
                          GROUP BY  Vchcode
                        ) AS b
                WHERE   a.Vchcode = b.Vchcode
                        AND a.Vchcode = @VchCode
                IF @@ROWCOUNT <= 0 
                    GOTO error  
            END

        UPDATE  dbo.tpx_SaleIndex
        SET     draft = 1
        WHERE   JTypeId = @ABranchid
                AND CHARINDEX(':' + keyid + ':', @BillCode) > 0  
        GOTO sucess
    END TRY
    BEGIN CATCH
        PRINT ERROR_MESSAGE()
        GOTO Error
    END CATCH
    sucess:
    BEGIN
    --判断系统配置是否要用单据自动连续编号  
        DECLARE @orderid INT ,
            @stats INT
        SET @orderid = 13  
        SET @stats = 0  
        EXEC FZBS_FZGetSysCon @orderid, @stats OUTPUT  
        IF @stats = 1 
            BEGIN  
                --SELECT TOP 1
                --        @BillDate = SaleDate
                --FROM    dbo.tpx_SaleIndex a
                --WHERE   CHARINDEX(':' + keyid + ':', @BillCode) > 0    
                EXEC FZBS_FZModifyVchnumber @vchtype, @BillDate  
            END  
	--处理虚拟库存
        IF EXISTS ( SELECT TOP 1
                            vchcode
                    FROM    dlyndx
                    WHERE   vchcode = @VchCode ) 
            BEGIN
                DECLARE @nRetVirtual INT
                EXEC @nRetVirtual= FZModifyVirtualGoods 'BakDly', '', @VchCode,
                    1 --  smallint
                IF @nRetVirtual < 0 
                    BEGIN
                        GOTO error
                    END
		
            END
        COMMIT TRAN
        RETURN 0
    END
    Error:
    BEGIN
        ROLLBACK TRAN
        RETURN -1
    END
    Error1:
    BEGIN
        ROLLBACK TRAN
        RETURN -2
    END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







/******************************************20131125********************************************/
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZBS_PosToDraftBill]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZBS_PosToDraftBill]
GO
--  ********************************************************************************************
--  ||   Create ：老罗  2012-10-19  
--  ||                                                                                   
--  ||   过程名称： FZBS_PosToDraftBill                                   
--  ||   过程功能： 零售小票结转成总部相关单据草稿
--  ||
--  ||==========================================================================================
-- return -1 结存失败，单据插入失败！
-- return -2 结存失败，你选择的单据已经被其他人结存！
CREATE PROCEDURE FZBS_PosToDraftBill
    (
      @ABranchid VARCHAR(50) ,  	--机构ID
      @BillCode VARCHAR(8000) = '' , 	--单据编号
      @ConditionStr VARCHAR(8000) = ''   --默认为空，各项目组的扩展参数,如果多于一个请各项目组各自用分隔符隔开
    )
AS 
    DECLARE @Btypeid VARCHAR(50)	--客户
    DECLARE @PosVchcode INT  
    DECLARE @Branchid VARCHAR(50)
    DECLARE @Branchid2 VARCHAR(50)    
    DECLARE @BranchType INT
    DECLARE @KtypeId VARCHAR(50)
    DECLARE @KtypeId2 VARCHAR(50)
    DECLARE @HandleManID VARCHAR(50)
    DECLARE @Etypeid VARCHAR(50)
    DECLARE @VchType INT
    DECLARE @VipCardID VARCHAR(50)
    DECLARE @PosUserCode VARCHAR(50)
    DECLARE @Dtypeid VARCHAR(50) --部门ID
    DECLARE @VchCode VARCHAR(50)
    DECLARE @DetailId INT
    DECLARE @InputName VARCHAR(50)
    DECLARE @site INT= 0
    DECLARE @tmpHandleManID VARCHAR(50)
    DECLARE @tmpetypeid VARCHAR(50)
    DECLARE @tmpType VARCHAR(1)
    DECLARE @tmpVipCardID VARCHAR(50)
    DECLARE @tmpCodeStr VARCHAR(8000)
    DECLARE @Period INT	
    
    DECLARE @CashSum NUMERIC(24, 10)
    DECLARE @BakMoneySum NUMERIC(24, 10)
    DECLARE @ReplaceCashSum NUMERIC(24, 10)
    DECLARE @CreditSum NUMERIC(24, 10)
    DECLARE @VipCardPay NUMERIC(24, 10)
    DECLARE @RetailChange NUMERIC(24, 10)
    DECLARE @RetailSum NUMERIC(24, 10)
    DECLARE @PromRtnReplaceCashSum NUMERIC(24, 10)
    DECLARE @SubValue VARCHAR(10) 
    DECLARE @BillDate VARCHAR(10)
    DECLARE @Keyid VARCHAR(50)   
    DECLARE @Tax NUMERIC(24, 10) 
    DECLARE @Number NVARCHAR(50) 
    DECLARE @Summary VARCHAR(200)= ''
    DECLARE @Comment VARCHAR(200)= ''
    DECLARE @CheckAndAccept BIT= 1
    

    SET @PosVchcode = 0
    	--单据类型
	--00000	所有单据   select * from vchtype
	--00001	零售单
	--00002	订金付入
	--00003	维修单
	--00004	补货申请单  --加盟店配货订单  发货类型为“补货  221
	--00005	退货申请单  --加盟商退货申请单，退货类型为“正常退货”
	--00006	盘点指令单
	--00007	盘点单
	--00008	调拨单      --同价调拨单
	--00009	调配单      --同价配货单，业务类型“调配”，发货类型“补货”
    SELECT TOP 1        -- 目前大部分POS单据不能实现合并成一张单据 老罗注释
            @PosVchcode = a.posvchcode ,
            @HandleManID = a.salesman ,
            @Etypeid = a.cashier ,
            @Btypeid = ISNULL(a.btypeid, '') ,
            @KtypeId = ISNULL(a.ktypeid, '') ,
            @KtypeId2 = ISNULL(a.ktypeid2, '') ,
            @VipCardID = a.VipCardId ,
            @PosUserCode = a.BillCode ,
            @BillDate = CONVERT(VARCHAR(10), CASE WHEN YEAR(a.CheckOutDate) < 2000
                                                  THEN a.saledate
                                                  WHEN vtypeid IN ( '00008',
                                                              '00009' )
                                                  THEN a.SaleDate
                                                  ELSE a.CheckOutDate
                                             END, 120) ,
            @VchType = CASE WHEN vtypeid = '00001' THEN 12
                            WHEN vtypeid = '00002' THEN 0   --暂时代替
                            WHEN vtypeid = '00003' THEN 0   --暂时代替
                            WHEN vtypeid = '00004' THEN 221
                            WHEN vtypeid = '00005' THEN 223
                            WHEN vtypeid = '00006' THEN 0   --暂时代替
                            WHEN vtypeid = '00007' THEN 0   --暂时代替
                            WHEN vtypeid = '00008' THEN 17
                            WHEN vtypeid = '00009' THEN 218
                            ELSE 0
                       END ,
            @Branchid = JTypeId ,
            @Keyid = keyid ,
            @Summary = Summary ,
            @Comment = Comment
    FROM    dbo.tpx_SaleIndex a
    WHERE   JTypeId = @ABranchid
            AND CHARINDEX(':' + Keyid + ':', @BillCode) > 0  

    SELECT TOP 1
            @Period = ISNULL(SubValue, 0)
    FROM    SysData
    WHERE   SubName = 'Period'  

    SELECT TOP 1
            @VipCardPay = COUNT(1)
    FROM    dbo.tpx_SaleVipList
    WHERE   CHARINDEX(':' + zbKeyid + ':', @BillCode) > 0  
    IF @KtypeId2 <> '' 
        SELECT TOP 1
                @Branchid2 = BranchID
        FROM    stock
        WHERE   typeid = @ktypeid
    SELECT TOP 1
            @SubValue = ISNULL(CashAsBillMoney, '0') ,
            @BranchType = BranchType ,
            @CheckAndAccept = CheckAndAccept
    FROM    dbo.Branch
    WHERE   branchid = @Branchid

    
    DECLARE @tmpName VARCHAR(100)
    DECLARE @tmpName1 VARCHAR(100)
    
    IF @HandleManID = ''
        OR @HandleManID IS NULL 
        BEGIN    
		--
            SELECT TOP 1
                    @HandleManID = b.etypeid
            FROM    dbo.tpx_SaleList a
                    INNER JOIN tpx_SaleManList b ON a.keyid = b.CBKeyId
            WHERE   ZBKeyId = @keyid
        END
    SET @tmpHandleManID = @HandleManID
    SET @tmpetypeid = @Etypeid
    SET @tmpVipCardID = @VipCardID
    SET @BakMoneySum = 0

    DECLARE @tmpPtypeid VARCHAR(100)

    SET @tmpCodeStr = @BillCode
    SELECT TOP 1
            @Dtypeid = Dtypeid
    FROM    dbo.Employee
    WHERE   TypeId = @HandleManID --取职员所属部门的ID
    
    DECLARE @dig_qty INT ,
        @dig_price INT ,
        @dig_total INT ,
        @dig_dis INT ,
        @dig_tax INT ,
        @dig_rate INT
    EXEC GetDig @dig_qty OUTPUT, @dig_price OUTPUT, @dig_total OUTPUT,
        @dig_dis OUTPUT, @dig_tax OUTPUT, @dig_rate OUTPUT


    BEGIN TRAN
    BEGIN TRY 
		--获取内部机构或加盟机构现金、银行卡、代金券对应科目及税率
        --DECLARE @ACash VARCHAR(50)
        --DECLARE @ACard VARCHAR(50)
        --DECLARE @ATicket VARCHAR(50)
        DECLARE @TaxRate NUMERIC(24, 10)= 0.00
        IF @BranchType <> 3 
            BEGIN
                --SELECT TOP 1
                --        @ACash = ATypeId
                --FROM    dbo.tpx_PosCashTypeConfig
                --WHERE   Jtypeid = @ABranchid
                --        AND Keyid = '00001'
                --SELECT TOP 1
                --        @ACard = ATypeId
                --FROM    dbo.tpx_PosCashTypeConfig
                --WHERE   Jtypeid = @ABranchid
                --        AND Keyid = '00002'
                --SELECT TOP 1
                --        @ATicket = ATypeId
                --FROM    dbo.tpx_PosCashTypeConfig
                --WHERE   Jtypeid = @ABranchid
                --        AND Keyid = '00003'
                SELECT TOP 1
                        @Tax = ROUND(Rate, @dig_tax)
                FROM    dbo.tpx_PosCashMain
                WHERE   Jtypeid = @ABranchid
					
            END
        IF @Summary = '' 
            SET @tmpName1 = '前台POS小票【' + @PosUserCode + '】'
        ELSE 
            SET @tmpName1 = @Summary
	    
        IF @ConditionStr = 'ht' 
            SET @tmpName1 = @tmpName1 + '，后台结存生成！'
	    
        IF @PosVchcode <> 0
            AND @VchType = 12 
            BEGIN

                IF @BranchType = 1
                    OR @BranchType = 7
                    OR @BranchType = 4 
                    SET @VchType = 12	-- 零售单
	                
                IF @BranchType = 3 
                    BEGIN
                        SET @VchType = 100	-- 代销零售单
                        SET @Tax = 0--代销零售单税率默认为0，再通过以面一句脚本更新（可能BtypeDistribute此机构的信息就会使用这个默认值0）                   
                        SELECT  @Tax = bd.TaxRate
                        FROM    Branch b
                                INNER JOIN dbo.BtypeDistribute bd ON b.Branchid = @Branchid
                                                              AND bd.BtypeId = b.BtypeId
                    END
	            
	           
                SET @Tax = ISNULL(@Tax, 0)
				--得到单据Number
                EXEC FN_VchNumber_Get @VchType, @BillDate, @ABranchid,
                    '127.0.0.1', 1, @Number OUTPUT

				-- 增加一个主表
                EXEC @VchCode = FZInsertDlyNdx 2, --Billtype 
                    @BillDate, -- @date
                    @Number, -- @number
                    @VchType, -- @vchtype
                    @tmpName1, -- @summary
                    @Comment, -- @comment
                    @Btypeid, -- @Btypeid
                    @tmpHandleManID, -- @Etypeid
                    @KtypeId, -- @KtypeId
                    '', -- @KtypeId2
                    0, -- @ifcheck
                    '', -- @checke
                    '', -- @accounte              
                    @tmpetypeid, -- @inputno
                    10, -- @draft
                    @tmpVipCardId, -- @vipcardid
                    100, -- @vipdiscount
                    0, -- @bartertype
                    @Dtypeid, -- @deptid
                    @BillDate, -- @limittime
                    '', -- @inputno1
                    '', -- @inputno2
                    '', -- @inputno3
                    100, -- @zddiscount
                    0, -- @zddiscountprice
                    0, -- @preferential
                    '', --@InputNo4
                    '', --@InputNo5
                    '', --科目ID
                    0, --@AtypeTotal 
                    '', --@ExpandId
                    '', --@ZoneId
                    '', --@ZoneId2
                    @site, -- @SiteId
                    @Branchid
				IF @VchCode<0 
				BEGIN
					  ROLLBACK TRAN
					  IF @VchCode<>-1
					  	  RETURN -3
					  ELSE
						  RETURN -1
				END
				--占用account字段设置POS小票生成草稿的标志，占用backmoney字段用来记录公共POS的单据积分金额
                UPDATE  DlyNdx
                SET     account = 'COMMONPOSLSJC' ,
                        BackMoney = ( SELECT    SUM(VipIntegral) AS jfje
                                      FROM      dbo.tpx_SaleIndex a
                                      WHERE     a.JTypeId = @ABranchid
                                                AND CHARINDEX(':' + keyid
                                                              + ':', @BillCode) > 0
                                    )
                WHERE   VchCode = @VchCode
    
  
                SELECT  a.ColorID ,	         SUM(a.DisCount) DisCount ,
				        a.DisCountRate ,    a.Price ,        a.PtypeID ,		   
				        SUM(a.Qty) Qty ,	a.RetailPrice ,  a.SizeID ,	  
				        SUM( a.Total )  Total ,
				        a.UnitId 
				        INTO  #tpx_SaleList_temp   
			    FROM    dbo.tpx_SaleList a
                        WHERE   CHARINDEX(':' + a.zbkeyid + ':', @tmpCodeStr) > 0
			    GROUP BY  a.ColorID ,	   
				        a.DisCountRate ,    a.Price ,       a.PtypeID ,			      
				        a.RetailPrice ,     		        a.SizeID ,	      
				        a.UnitId 
				HAVING  SUM(a.Qty)<>0   
   
                INSERT  INTO [dbo].[bakdly]
                        ( [vchcode] ,
                          [atypeId] ,
                          [btypeId] ,
                          [etypeId] ,
                          [ktypeId] ,
                          [branchid] ,
                          vipcardid ,
                          billtype ,
                          RetailPrice ,
                          [PtypeId] ,
                          [Qty] ,
                          [discount] ,
                          [discountprice] ,
                          [costtotal] ,
                          [costPrice] ,
                          [price] ,
                          [total] ,
                          [TaxPrice] ,
                          [TaxTotal] ,
                          [comment] ,
                          [date] ,
                          [usedtype] ,
                          [period] ,
                          [tax_total] ,
                          [tax] ,
                          [discounttotal] ,
                          [costmode] ,
                          [vchtype] ,
                          [Dtypeid] ,
                          [colorid] ,
                          [VipDiscount] ,
                          [convert] ,
                          [roworder] ,
                          [bargainTotal] ,
                          [ifSupply] ,
                          [SaleMoney] ,
                          [MarketDiscount] ,
                          [MarketDiscount1] ,
                          [salemode] ,
                          [PHRows]
						)
                        SELECT  @VchCode ,
                                '0000100001' ,
                                @Btypeid ,
                                @tmpHandleManID ,
                                @KtypeId ,
                                @Branchid ,
                                @tmpVipCardId ,
                                2 ,
                                RetailPrice ,
                                Ptypeid ,
                                SUM(Qty) ,
                                100 ,
                                RetailPrice ,
                                0 ,
                                0 ,
                                RetailPrice ,
                                0 ,----total
                                CASE @BranchType
                                  WHEN 3
                                  THEN ROUND(ISNULL(SUM(a.Total), 0) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100
                                             / ( CASE WHEN SUM(Qty) = 0 THEN 1
                                                      ELSE SUM(qty)
                                                 END ), @dig_price)
                                  ELSE ROUND(ISNULL(SUM(a.Total), 0)
                                             / ( CASE WHEN SUM(Qty) = 0 THEN 1
                                                      ELSE SUM(qty)
                                                 END ), @dig_price)                --税价
                                END ,
                                0 ,--税额----TaxTotal 
                                '' ,
                                @BillDate ,
                                1 ,
                                @Period ,
                                CASE @BranchType
                                  WHEN 3
                                  THEN ROUND(SUM(ISNULL(a.Total, 0)) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100,
                                             @dig_total)
                                  ELSE ROUND(SUM(ISNULL(a.Total, 0)),
                                             @dig_total)	       -- 含税金额 -----POS 那边的Total 是含税的 tax_total
                                END ,
                                ISNULL(@Tax, 0.00) ,
                                price ,  -- discounttotal 本来这里该直接写0 此处暂借用来写折后价，
										 --	是为了Group by ,不然插bakdlydetail时就要失去关联
										 -- 在后面要更正的
                                0 ,
                                @VchType ,
                                '' ,--dtypeid
                                ColorID ,
                                100 ,--vipdiscount
                                0 ,--convert
                                0 ,
                                0 ,-- 成交金额 扣税-----bargainTotal
                                0 ,
                                0 , ------Salemoney
                                CASE @BranchType
                                  WHEN 3
                                  THEN ISNULL(( SELECT  b.Price
                                                FROM    ptypeprice b
                                                WHERE   b.ptypeId = a.ptypeid
                                                        AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                              ), 0)
                                  ELSE 0
                                END ,
                                CASE @BranchType
                                  WHEN 3
                                  THEN ISNULL(( SELECT  b.Price
                                                FROM    ptypeprice b
                                                WHERE   b.ptypeId = a.ptypeid
                                                        AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                              ), 0)
                                  ELSE 0
                                END ,
                                0 ,
                                ROW_NUMBER() OVER ( ORDER BY ColorID ) --获得行号，对应PHrows字段
                        FROM   #tpx_SaleList_temp a
                        GROUP BY Ptypeid ,
                                RetailPrice ,
                                price ,
                                ColorID ,
                                SIGN(QTY)
                --写三级明细                
            	-----*******************************************测试用    
                --SELECT *FROM bakdly WHERE vchcode=@VchCode
                --SELECT  b.DlyOrder ,
                --                a.SizeID ,
                --                a.ColorID ,
                --                SUM(a.Qty) AS qty ,
                --                0 ,
                --                ROUND(CAST(CAST(SUM(a.Qty) AS NUMERIC(24,10)) * a.RetailPrice AS NUMERIC(24,10)), @dig_total) ,----total
                --                CASE @BranchType
                --                  WHEN 3
                --                  THEN ROUND(CAST(Cast(SUM(a.Total) AS NUMERIC(24,10)) * ( 100
                --                                              - ISNULL(( SELECT
                --                                              b.Price
                --                                              FROM
                --                                              ptypeprice b
                --                                              WHERE
                --                                              b.ptypeId = a.ptypeid
                --                                              AND b.PriceTypeId = ( SELECT
                --                                              c.MarketDiscountID
                --                                              FROM
                --                                              btypedistribute c
                --                                              WHERE
                --                                              c.btypeid = @Btypeid
                --                                              )
                --                                              ), 0) ) / 100 AS NUMERIC(24,10)),
                --                             @dig_total)
                --                       - ROUND(CAST(Cast(SUM(a.Total) AS NUMERIC(24,10) ) * ( 100
                --                                              - ISNULL(( SELECT
                --                                              b.Price
                --                                              FROM
                --                                              ptypeprice b
                --                                              WHERE
                --                                              b.ptypeId = a.ptypeid
                --                                              AND b.PriceTypeId = ( SELECT
                --                                              c.MarketDiscountID
                --                                              FROM
                --                                              btypedistribute c
                --                                              WHERE
                --                                              c.btypeid = @Btypeid
                --                                              )
                --                                              ), 0) ) / 100
                --                               / ( 1 + ISNULL(@Tax, 0) / 100 ) AS NUMERIC(24,10)),
                --                               @dig_total)
                --                  ELSE ROUND(cast(SUM(a.Total) AS NUMERIC(24,10)),
                --                             @dig_total)
                --                       - ROUND(CAST(Cast(SUM(a.Total) AS NUMERIC(24,10) ) / ( 1
                --                                              + @TaxRate / 100 ) AS NUMERIC(24,10)),
                --                               @dig_total)
                --                END ,  --税额----TaxTotal 
                --                CASE @BranchType
                --                  WHEN 3
                --                  THEN ROUND(CAST(Cast(SUM(a.Total) AS NUMERIC(24,10) ) * ( 100
                --                                              - ISNULL(( SELECT
                --                                              b.Price
                --                                              FROM
                --                                              ptypeprice b
                --                                              WHERE
                --                                              b.ptypeId = a.ptypeid
                --                                              AND b.PriceTypeId = ( SELECT
                --                                              c.MarketDiscountID
                --                                              FROM
                --                                              btypedistribute c
                --                                              WHERE
                --                                              c.btypeid = @Btypeid
                --                                              )
                --                                              ), 0) ) / 100 AS NUMERIC(24,10)),
                --                             @dig_total)
                --                  ELSE ROUND(ISNULL(SUM(a.Total), 0),
                --                             @dig_total)
                --                END ,-- 含税金额 -----tax_total
                --                CASE @BranchType
                --                  WHEN 3
                --                  THEN ROUND(CAST(Cast(SUM(a.Total) as numeric(24,10)) * ( 100
                --                                              - ISNULL(( SELECT
                --                                              b.Price
                --                                              FROM
                --                                              ptypeprice b
                --                                              WHERE
                --                                              b.ptypeId = a.ptypeid
                --                                              AND b.PriceTypeId = ( SELECT
                --                                              c.MarketDiscountID
                --                                              FROM
                --                                              btypedistribute c
                --                                              WHERE
                --                                              c.btypeid = @Btypeid
                --                                              )
                --                                              ), 0) ) / 100
                --                             / ( 1 + @Tax / 100 ) AS NUMERIC(24,10)), @dig_total)
                --                  ELSE ROUND(Cast(Cast(SUM(a.Total) AS NUMERIC(24,10)) / ( 1
                --                                              + @TaxRate / 100 ) AS NUMERIC(24,10)),
                --                             @dig_total)
                --                END ,---BargainTotal =含税金额/(1+税率/100)
                --                CASE @BranchType
                --                  WHEN 3
                --                  THEN ----
                --                       ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24,10)) *a.RetailPrice AS NUMERIC(24,10)),
                --                             @dig_total) - ISNULL(SUM(a.Total),
                --                                              0)
                --                  ELSE ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24,10)) *a.RetailPrice AS NUMERIC(24,10)),
                --                             @dig_total)
                --                       - ROUND(Cast(Cast(SUM(a.Total) AS NUMERIC(24,10)) / ( 1
                --                                              + @Tax / 100 ) AS NUMERIC(24,10)),
                --                               @dig_total)
                --                END ,--convert
                --                ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24,10)) *a.RetailPrice AS NUMERIC(24,10)), @dig_total) ,--DiscountTotal
                --                ISNULL(SUM(a.Total), 0) , --salemoney
                --                1 ,
                --                b.PHRows ,
                --                @VchCode
                --        FROM    dbo.tpx_SaleList a
                --                INNER JOIN bakdly b ON a.Ptypeid = b.Ptypeid
                --                                       AND a.RetailPrice = b.Price
                --                                       AND a.ColorID = B.ColorID
                --                                       AND a.price = b.discounttotal
                --                                       AND b.Vchcode = @VchCode
                --                                       --AND SIGN(SUM(a.QTY))=SIGN(b.qty)
                --        WHERE   CHARINDEX(':' + a.ZBKeyId + ':', @tmpCodeStr) > 0
                --        GROUP BY a.ptypeid ,
                --                a.ColorID ,
                --                a.SizeID ,
                --                b.DlyOrder ,
                --                a.RetailPrice ,
                --                a.price,
                --                SIGN(a.qty),
                --                b.qty, 
                --                b.PHRows     
                --        HAVING  SIGN(SUM(a.QTY))=SIGN(b.qty)          
                ----*******************************************测试用
                INSERT  INTO bakDlydetail
                        ( dlyorder ,
                          sizeid ,
                          colorid ,
                          Qty ,
                          CostTotal ,
                          Total ,
                          TaxTotal ,
                          Tax_Total ,
                          BargainTotal ,
                          [Convert] ,
                          DiscountTotal ,
                          SaleMoney ,
                          Usedtype ,
                          PHRows ,
                          Vchcode
						)
                        SELECT  b.DlyOrder ,
                                a.SizeID ,
                                a.ColorID ,
                                SUM(a.Qty) AS qty ,
                                0 ,
                                ROUND(CAST(CAST(SUM(a.Qty) AS NUMERIC(24, 10))
                                      * a.RetailPrice AS NUMERIC(24, 10)),
                                      @dig_total) ,----total
                                CASE @BranchType
                                  WHEN 3
                                  THEN ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100 AS NUMERIC(24,
                                                              10)), @dig_total)
                                       - ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100
                                               / ( 1 + ISNULL(@Tax, 0) / 100 ) AS NUMERIC(24,
                                                              10)), @dig_total)
                                  ELSE ROUND(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)), @dig_total)
                                       - ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) / ( 1
                                                              + @Tax / 100 ) AS NUMERIC(24,
                                                              10)), @dig_total)
                                END ,  --税额----TaxTotal 
                                CASE @BranchType
                                  WHEN 3
                                  THEN ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100 AS NUMERIC(24,
                                                              10)), @dig_total)
                                  ELSE ROUND(ISNULL(SUM(a.Total), 0),
                                             @dig_total)
                                END ,-- 含税金额 -----tax_total
                                CASE @BranchType
                                  WHEN 3
                                  THEN ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) * ( 100
                                                              - ISNULL(( SELECT
                                                              b.Price
                                                              FROM
                                                              ptypeprice b
                                                              WHERE
                                                              b.ptypeId = a.ptypeid
                                                              AND b.PriceTypeId = ( SELECT
                                                              c.MarketDiscountID
                                                              FROM
                                                              btypedistribute c
                                                              WHERE
                                                              c.btypeid = @Btypeid
                                                              )
                                                              ), 0) ) / 100
                                             / ( 1 + @Tax / 100 ) AS NUMERIC(24,
                                                              10)), @dig_total)
                                  ELSE ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) / ( 1
                                                              + @Tax / 100 ) AS NUMERIC(24,
                                                              10)), @dig_total)
                                END ,---BargainTotal =含税金额/(1+税率/100)
                                CASE @BranchType
                                  WHEN 3
                                  THEN ----
                                       ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24,
                                                              10))
                                             * a.RetailPrice AS NUMERIC(24, 10)),
                                             @dig_total) - ISNULL(SUM(a.Total),
                                                              0)
                                  ELSE ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24,
                                                              10))
                                             * a.RetailPrice AS NUMERIC(24, 10)),
                                             @dig_total)
                                       - ROUND(CAST(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)) / ( 1
                                                              + @Tax / 100 ) AS NUMERIC(24,
                                                              10)), @dig_total)
                                END ,--convert
                                ROUND(CAST(CAST(SUM(a.qty) AS NUMERIC(24, 10))
                                      * a.RetailPrice AS NUMERIC(24, 10)),
                                      @dig_total) ,--DiscountTotal
                                ISNULL(ROUND(CAST(SUM(a.Total) AS NUMERIC(24,
                                                              10)), @dig_total),
                                       0) , --salemoney
                                1 ,
                                b.PHRows ,
                                @VchCode
                        FROM    #tpx_SaleList_temp a
                                INNER JOIN bakdly b ON a.Ptypeid = b.Ptypeid
                                                       AND a.RetailPrice = b.Price
                                                       AND a.ColorID = B.ColorID
                                                       AND a.price = b.discounttotal
                                                       AND b.Vchcode = @VchCode
                                                       --AND SIGN(SUM(a.QTY))=SIGN(b.qty)
                        GROUP BY a.ptypeid ,
                                a.ColorID ,
                                a.SizeID ,
                                b.DlyOrder ,
                                a.RetailPrice ,
                                a.price ,
                                SIGN(a.qty) ,
                                b.qty ,
                                b.PHRows
                        HAVING  SIGN(SUM(a.QTY)) = SIGN(b.qty)          
                       
	                             
                IF EXISTS ( SELECT  1            --POS小票类单据生成总部草稿以后，更改POS小票类单据的状态
                            FROM    dbo.tpx_SaleIndex
                            WHERE   draftvchCode > 0
                                    AND CHARINDEX(':' + keyid + ':',
                                                  @tmpCodeStr) > 0 ) 
                    GOTO error1  
                ELSE 
                    UPDATE  dbo.tpx_SaleIndex
                    SET     draftvchCode = @VchCode
                    WHERE   Jtypeid = @ABranchid
                            AND CHARINDEX(':' + keyid + ':', @tmpCodeStr) > 0      
				--此处收款科目是动态的，根据用户设置可能有很多种以前的老代码删除了 modify by 老罗 2012-11-12
 
				-- 写收款科目

                IF ( @VchType = 12
                     OR @VchType = 13
                   )
                    AND @RetailSum <> 0
                    AND @SubValue = '1' 
                    UPDATE  dbo.DlyNdx
                    SET     AtypeTotal = ISNULL(@RetailSum, 0)
                    WHERE   VchCode = @VchCode
			   -- modify by 老罗 2012-11-12 因为是动态的科目，所以直接取pos的付款方式表tpx_salepaylist中记录
	   
                IF @BranchType <> 3 
                    BEGIN
                        IF EXISTS ( SELECT  1
                                    FROM    dbo.tpx_SalePayList
                                    WHERE   CHARINDEX(':' + ZBkeyid + ':',
                                                      @tmpCodeStr) > 0 ) 
                            BEGIN
                                INSERT  INTO [dbo].[bakdly]
                                        ( [vchcode] ,
                                          [atypeId] ,
                                          [btypeId] ,
                                          [etypeId] ,
                                          [ktypeId] ,
                                          [PtypeId] ,
                                          [branchid] ,
                                          [billtype ] ,
                                          [Qty] ,
                                          [discount] ,
                                          [discountprice] ,
                                          [costtotal] ,
                                          [costPrice] ,
                                          [price] ,
                                          [total] ,
                                          [TaxPrice] ,
                                          [TaxTotal] ,
                                          [comment] ,
                                          [date] ,
                                          [usedtype] ,
                                          [period] ,
                                          [tax_total] ,
                                          [tax] ,
                                          [discounttotal] ,
                                          [costmode] ,
                                          [vchtype] ,
                                          [unit] ,
                                          [Dtypeid] ,
                                          [colorid] ,
                                          [VipDiscount] ,
                                          [convert] ,
                                          [roworder] ,
                                          [bargainTotal] ,
                                          [ifSupply]
									    )
                                        SELECT  @VchCode ,
                                                p.AtypeId ,
                                                @Btypeid ,
                                                @tmpetypeid ,
                                                @KtypeId ,
                                                '' ,
                                                @branchid ,
                                                2 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                SUM(Total) ,
                                                0 ,
                                                0 ,
                                                CASE WHEN p.Keyid='00003' THEN 'systemDJQ' ELSE '' END,
                                                @BillDate ,
                                                '2' ,
                                                @Period ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                @VchType ,
                                                0 ,
                                                '' ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0
                                        FROM    dbo.tpx_SalePayList s
                                                INNER JOIN dbo.tpx_PosCashTypeConfig p ON s.akeyid = p.keyid
                                                              AND p.Jtypeid = @Branchid
                                        WHERE   CHARINDEX(':' + s.ZBkeyid
                                                          + ':', @tmpCodeStr) > 0
                                                AND s.AKeyId <> '00004'
                                        GROUP BY p.AtypeId ,p.Keyid                   
                                
                            END 
                        IF ABS(@vipcardpay) > 0 
                            BEGIN
                                INSERT  INTO [dbo].[bakdly]
                                        ( [vchcode] ,
                                          [atypeId] ,
                                          [btypeId] ,
                                          [etypeId] ,
                                          [ktypeId] ,
                                          [PtypeId] ,
                                          [branchid] ,
                                          vipcardid ,
                                          billtype ,
                                          [Qty] ,
                                          [discount] ,
                                          [discountprice] ,
                                          [costtotal] ,
                                          [costPrice] ,
                                          [price] ,
                                          [total] ,
                                          [TaxPrice] ,
                                          [TaxTotal] ,
                                          [comment] ,
                                          [date] ,
                                          [usedtype] ,
                                          [period] ,
                                          [tax_total] ,
                                          [tax] ,
                                          [discounttotal] ,
                                          [costmode] ,
                                          [vchtype] ,
                                          [unit] ,
                                          [Dtypeid] ,
                                          [colorid] ,
                                          [VipDiscount] ,
                                          [convert] ,
                                          [roworder] ,
                                          [bargainTotal] ,
                                          [ifSupply]
										)
                                        SELECT  @VchCode ,
                                                '0000299999' ,
                                                @Btypeid ,
                                                @tmpetypeid ,
                                                @KtypeId ,
                                                '' ,
                                                @branchid ,
                                                vipid ,
                                                2 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                CASE WHEN SIGN(c.FinallyTotal) >= 0
                                                     THEN a.Total
                                                     ELSE -1 * a.Total
                                                END ,
                                                0 ,
                                                0 ,
                                                '卡号:' + cardno + ' 持卡人:'
                                                + holderName ,
                                                @BillDate ,
                                                '2' ,
                                                @Period ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                @VchType ,
                                                0 ,
                                                '' ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0 ,
                                                0
                                        FROM    dbo.tpx_SaleVipList a
                                                INNER JOIN dbo.tpx_SaleIndex c ON a.ZBKeyId = c.keyId
                                                LEFT JOIN vipcards b ON a.vipid = b.cardid
                                        WHERE   CHARINDEX(':' + a.ZBKeyId
                                                          + ':', @tmpCodeStr) > 0 
                              
                            END
                    END
				
                       
	                   
                UPDATE  bakdly
                SET     total = b.total ,
                        TaxTotal = b.TaxTotal ,
                        Tax_Total = b.Tax_Total ,
                        BargainTotal = b.BargainTotal ,
                        [Convert] = b.[Convert] ,
                        DiscountTotal = b.DiscountTotal ,
                        SaleMoney = b.SaleMoney
                FROM    bakdly a ,
                        ( SELECT    DlyOrder ,
                                    ROUND(CAST(SUM(total) AS NUMERIC(24, 10)),
                                          @dig_total) AS total ,
                                    ROUND(CAST(SUM(TaxTotal) AS NUMERIC(24, 10)),
                                          @dig_Total) AS TaxTotal ,
                                    ROUND(CAST(SUM(Tax_Total) AS NUMERIC(24,
                                                              10)), @dig_total) AS Tax_Total ,
                                    ROUND(CAST(SUM(BargainTotal) AS NUMERIC(24,
                                                              10)), @dig_total) AS BargainTotal ,
                                    ROUND(CAST(SUM([Convert]) AS NUMERIC(24,
                                                              10)), @dig_total) AS [Convert] ,
                                    ROUND(CAST(SUM(DiscountTotal) AS NUMERIC(24,
                                                              10)), @dig_total) AS DiscountTotal ,
                                    ROUND(CAST(SUM(SaleMoney) AS NUMERIC(24,
                                                              10)), @dig_total) AS SaleMoney
                          FROM      bakdlydetail
                          WHERE     vchcode = @VchCode
                          GROUP BY  DlyOrder
                        ) AS b
                WHERE   a.vchcode = @VchCode
                        AND a.dlyorder = b.dlyorder 
	            
                UPDATE  a
                SET     a.phrows = b.phrows
                FROM    bakdlydetail a
                        INNER JOIN bakdly b ON a.vchcode = b.vchcode
                                               AND a.DlyOrder = b.DlyOrder
                WHERE   a.vchcode = @VchCode
	            
                UPDATE  dbo.DlyNdx
                SET     qty = ROUND(ISNULL(b.qty, 0.00), @dig_qty) ,
                        total = ROUND(ISNULL(b.total, 0.00), @dig_total)
                FROM    dlyndx a ,
                        ( SELECT    Vchcode ,
                                    CAST(SUM(qty) AS NUMERIC(24, 10)) AS qty ,
                                    CAST(SUM(SaleMoney) AS NUMERIC(24, 10)) AS total
                          FROM      bakdly
                          WHERE     UsedType = 1
                                    AND vchcode = @VchCode
                          GROUP BY  Vchcode
                        ) AS b
                WHERE   a.Vchcode = b.Vchcode
                        AND a.Vchcode = @VchCode
     --           --特殊处理只在结算时录入vip卡的情况（取结算第一张卡的卡号作为主表的vip卡） 此处pos端处理了
     --           IF exists(SELECT 1 FROM bakdly a INNER JOIN dlyndx d ON a.vchcode=d.vchcode 
					--	  WHERE a.VipCardID<>0 AND d.VipCardID=0 AND d.vchcode=@VchCode)
			  --  BEGIN
					--UPDATE a SET a.vipcardid=b.vipcardid FROM dlyndx a INNER JOIN 
					--	(select TOP 1 VipCardID,vchcode FROM bakdly WHERE VipCardID<>0 AND vchcode=@VchCode) b 
					--		ON a.vchcode=b.vchcode
					--WHERE b.VipCardID<>0 AND a.VipCardID=0 AND a.vchcode=@VchCode
			  --  END
                      
                --特殊处理代金卷的问题 (零售单一定会收款)
                
                IF EXISTS ( SELECT TOP 1
                                    1
                            FROM    bakdly
                            WHERE   Vchcode = @VchCode
                                    AND Comment = 'systemDJQ' ) 
                    BEGIN
						declare @total numeric(24,10) --付款总金额
						declare @salemoney numeric(24,10) --单据总金额
						select @total = sum(case when  NOT ptypeid IS NULL
																	  AND ptypeid <> '' 
																	  then  0 else total end),
								   @salemoney = sum(case when   NOT ptypeid IS NULL
																	  AND ptypeid <> ''
																	  then  salemoney else 0 end)
						From      bakdly
						WHERE     Vchcode = @VchCode

						if abs(@total) <> abs(@salemoney) 
						begin
						  update bakdly set total = total + (@salemoney - @total)
						  where Vchcode = @VchCode and atypeid = '000040000300006' 
						end
                    
                    
                        --IF EXISTS ( SELECT  SUM(Total)
                        --            FROM    ( SELECT    SUM(CASE
                        --                                      WHEN ( NOT ptypeid IS NULL
                        --                                      AND ptypeid <> ''
                        --                                      )
                        --                                      THEN -salemoney
                        --                                      ELSE Total
                        --                                    END) AS Total ,
                        --                                ptypeid ,
                        --                                SUM(qty) qty
                        --                      FROM      bakdly
                        --                      WHERE     Vchcode = @VchCode
                        --                      GROUP BY  ptypeid
                        --                    ) c
                        --            HAVING  SUM(Total) > 0
                        --                    AND SUM(qty) >= 0 ) 
                        --    BEGIN
                        --        UPDATE  a
                        --        SET     a.Total = a.Total - b.Total
                        --        FROM    bakdly a ,
                        --                ( SELECT    SUM(Total) Total ,
                        --                            vchcode
                        --                  FROM      ( SELECT  SUM(CASE
                        --                                      WHEN ( NOT ptypeid IS NULL
                        --                                      AND ptypeid <> ''
                        --                                      )
                        --                                      THEN -salemoney
                        --                                      ELSE Total
                        --                                      END) AS Total ,
                        --                                      ptypeid ,
                        --                                      Vchcode ,
                        --                                      SUM(qty) qty
                        --                              FROM    bakdly
                        --                              WHERE   Vchcode = @VchCode
                        --                              GROUP BY ptypeid ,
                        --                                      vchcode
                        --                            ) c
                        --                  GROUP BY  vchcode
                        --                  HAVING    SUM(Total) > 0
                        --                            AND SUM(qty) >= 0
                        --                ) b
                        --        WHERE   a.Vchcode = @VchCode
                        --                AND a.Vchcode = b.vchcode
                        --                AND a.Comment = 'systemDJQ'
                        --    END    
                        --IF EXISTS ( SELECT  SUM(Total)
                        --            FROM    ( SELECT    SUM(CASE
                        --                                      WHEN ( NOT ptypeid IS NULL
                        --                                      AND ptypeid <> ''
                        --                                      )
                        --                                      THEN -salemoney
                        --                                      ELSE Total
                        --                                    END) AS Total ,
                        --                                ptypeid ,
                        --                                SUM(qty) AS qty
                        --                      FROM      bakdly
                        --                      WHERE     Vchcode = @VchCode
                        --                      GROUP BY  ptypeid
                        --                    ) c
                        --            HAVING  SUM(Total) < 0
                        --                    AND SUM(qty) <= 0 ) 
                        --    BEGIN
                        --        UPDATE  a
                        --        SET     a.Total = a.Total - b.Total
                        --        FROM    bakdly a ,
                        --                ( SELECT    SUM(Total) Total ,
                        --                            vchcode
                        --                  FROM      ( SELECT  SUM(CASE
                        --                                      WHEN ( NOT ptypeid IS NULL
                        --                                      AND ptypeid <> ''
                        --                                      )
                        --                                      THEN -salemoney
                        --                                      ELSE Total
                        --                                      END) AS Total ,
                        --                                      ptypeid ,
                        --                                      vchcode ,
                        --                                      SUM(qty) qty
                        --                              FROM    bakdly
                        --                              WHERE   Vchcode = @VchCode
                        --                              GROUP BY ptypeid ,
                        --                                      vchcode
                        --                            ) c
                        --                  GROUP BY  vchcode
                        --                  HAVING    SUM(Total) < 0
                        --                            AND SUM(qty) <= 0
                        --                ) b
                        --        WHERE   a.Vchcode = @VchCode
                        --                AND a.Vchcode = b.vchcode
                        --                AND a.Comment = 'systemDJQ'
                        --    END    
                    END
            END
		-- 新增一个调拨或配送单草稿
	    
        IF @PosVchcode <> 0
            AND @VchType IN ( 17, 218 ) 
            BEGIN
		
			 --得到单据Number
				
                EXEC FN_VchNumber_Get @VchType, @BillDate, @ABranchid,
                    '127.0.0.1', 1, @Number OUTPUT

				--判断是否启用配送验收流程 配送单过账的时候要判断此处不用了2012-10-29
				--DECLARE @VerifyFlow BIT
				--SELECT TOP 1 @VerifyFlow=CheckAndAccept FROM dbo.Branch WHERE BranchID=@Branchid2
				-- 增加一个主表
                EXEC @VchCode = FZInsertDlyNdx 3, --Billtype 
                    @BillDate, -- @date
                    @Number, -- @number
                    @VchType, -- @vchtype
                    @tmpName1, -- @summary
                    @comment, -- @comment
                    @Btypeid, -- @Btypeid
                    @tmpHandleManID, -- @Etypeid
                    @KtypeId, -- @KtypeId
                    @Ktypeid2, -- @KtypeId2
                    0, -- @ifcheck
                    '', -- @checke
                    'COMMONPOSLSJC', -- @accounte              
                    @tmpetypeid, -- @inputno
                    10, -- @draft
                    @tmpVipCardId, -- @vipcardid
                    100, -- @vipdiscount
                    0, -- @bartertype
                    @Dtypeid, -- @deptid
                    '', -- @limittime
                    @tmpetypeid, -- @inputno1
                    '', -- @inputno2
                    '', -- @inputno3
                    0, -- @zddiscount
                    0, -- @zddiscountprice
                    0, -- @preferential
                    '', --@InputNo4
                    '', --@InputNo5
                    '', --科目ID
                    0, --@AtypeTotal 
                    '', --@ExpandId
                    '', --@ZoneId
                    '', --@ZoneId2
                    @site, -- @SiteId
                    @Branchid2, 0, --@Total
                    '', --@Xw_Vsf1   
                    '', --@Xw_Vsf2
                    '', --@Xw_Vsf3
                    '', --@Xw_Vsf4
                    '', --@Xw_Vsf5
                    '', --@VchOrderList
                    @BranchId, --@BranchId2
                    3   --@phid
                IF @VchCode<0 
				BEGIN
					  ROLLBACK TRAN
					  IF @VchCode<>-1
					  	  RETURN -3
					  ELSE
						  RETURN -1
				END
                INSERT  INTO [dbo].[bakdly]
                        ( [vchcode] ,
                          [atypeId] ,
                          [btypeId] ,
                          [etypeId] ,
                          [ktypeId] ,
                          [branchid] ,
                          vipcardid ,
                          billtype ,
                          RetailPrice ,
                          [PtypeId] ,
                          [Qty] ,
                          [discount] ,
                          [discountprice] ,
                          [costtotal] ,
                          [costPrice] ,
                          [price] ,
                          [total] ,
                          [TaxPrice] ,
                          [TaxTotal] ,
                          [comment] ,
                          [date] ,
                          [usedtype] ,
                          [period] ,
                          [tax_total] ,
                          [tax] ,
                          [discounttotal] ,
                          [costmode] ,
                          [vchtype] ,
                          [Dtypeid] ,
                          [colorid] ,
                          [VipDiscount] ,
                          [convert] ,
                          [roworder] ,
                          [bargainTotal] ,
                          [ifSupply] ,
                          [SaleMoney] ,
                          [MarketDiscount] ,
                          [MarketDiscount1] ,
                          [salemode] ,
                          [PHRows] ,
                          OpID ,
                          Unit
		                
						)
						--Total,tax_total,bargaintotal,DiscountTotal,salemoney这五种金额直接写当前库存成本价，没有取到则写0
						--二级主表除零售金额和单价以外都写0，写完三级明细后反写二级明细
                        SELECT  @VchCode ,
                                '0000100001' ,
                                @Btypeid ,
                                @tmpHandleManID ,
                                @KtypeId ,
                                @Branchid2 ,
                                @tmpVipCardId ,
                                3 ,
                                RetailPrice ,
                                Ptypeid ,
                                SUM(Qty) ,
                                100 ,          --discount
                                0 ,            --discountprice   
                                0 ,            --costTotal
                                0 ,            --Costprice
                                0 ,            --price
                                0 ,            --total
                                0 ,            --Taxprice
                                0 ,            --TaxTotal 税额---- 
                                a.Comment ,
                                @BillDate ,
                                1 ,            --usedtype
                                @Period ,            --[period]
                                0 ,              --tax_total  含税金额 ---
                                ISNULL(@Tax, 0) ,--Tax
                                0 ,          -- discounttotal 
                                0 ,              --Costmode
                                @VchType ,
                                @dtypeid ,       --Dtypeid
                                ColorID ,
                                100 ,            --vipdiscount
                                0 ,              --convert
                                0 ,              --roworder
                                0 ,              --bargainTotal 成交金额 扣税-----
                                0 ,              --ifSupply
                                0 ,              --Salemoney
                                100 ,            --MarketDiscount  配送和调拨不用考虑商场扣率问题
                                100 ,            --MarketDiscount1
                                0 ,
                                ROW_NUMBER() OVER ( ORDER BY ColorID ) , --获得行号，对应PHrows字段
                                3 ,
                                a.Unitid
                        FROM    dbo.tpx_ReplenishList a
                        WHERE   CHARINDEX(':' + a.zbkeyid + ':', @tmpCodeStr) > 0
                        GROUP BY Ptypeid ,
                                RetailPrice ,
                                ColorID ,
                                a.Unitid ,
                                a.Comment
	                             
                IF EXISTS ( SELECT  1
                            FROM    dbo.tpx_SaleIndex
                            WHERE   draftvchCode > 0
                                    AND CHARINDEX(':' + keyid + ':',
                                                  @tmpCodeStr) > 0 ) 
                    GOTO error1  
                ELSE 
                    UPDATE  dbo.tpx_SaleIndex
                    SET     draftvchCode = @VchCode
                    WHERE   Jtypeid = @ABranchid
                            AND CHARINDEX(':' + keyid + ':', @tmpCodeStr) > 0      
	-----*******************************************测试用			
				--SELECT *FROM bakdly WHERE Vchcode=@VchCode
				--SELECT  b.DlyOrder ,
    --                            a.SizeID ,
    --                            a.ColorID ,
    --                            SUM(a.Qty) AS qty ,
    --                            0 ,
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) ,----total
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) ,--税额----TaxTotal 
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) , -- 含税金额 -----tax_total
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) , ---BargainTotal
    --                            0 ,
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) ,--DiscountTotal
    --                            ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,10)),
    --                                  @dig_total) , --SaleMoney
    --                            1 ,
    --                            b.PHRows ,
    --                            @VchCode
    --                    FROM    dbo.tpx_ReplenishList a
    --                            INNER JOIN bakdly b ON a.Ptypeid = b.Ptypeid
    --                                                   AND b.Vchcode = @VchCode
    --                                                   AND a.ColorID = B.ColorID
    --                                                   AND a.Comment=b.Comment
    --                            LEFT JOIN Goodsstocks g ON b.ktypeid = g.KtypeId
    --                                                       AND b.PtypeId = g.PtypeId
    --                    WHERE   CHARINDEX(':' + a.ZBKeyId + ':', @tmpCodeStr) > 0
    --                    GROUP BY a.ptypeid ,
    --                            a.ColorID ,
    --                            a.SizeID ,
    --                            b.DlyOrder ,
    --                            g.price ,
    --                            a.Comment,
    --                            b.PHRows
    -----*******************************************测试用
                INSERT  INTO bakDlydetail
                        ( dlyorder ,
                          sizeid ,
                          colorid ,
                          Qty ,
                          CostTotal ,
                          Total ,
                          TaxTotal ,
                          Tax_Total ,
                          BargainTotal ,
                          [Convert] ,
                          DiscountTotal ,
                          SaleMoney ,
                          Usedtype ,
                          PHRows ,
                          Vchcode
						)
                        SELECT  b.DlyOrder ,
                                a.SizeID ,
                                a.ColorID ,
                                SUM(a.Qty) AS qty ,
                                0 ,
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) ,----total
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) ,--税额----TaxTotal 
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) , -- 含税金额 -----tax_total
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) , ---BargainTotal
                                0 ,
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) ,--DiscountTotal
                                ROUND(CAST(SUM(a.Qty) * ISNULL(g.price, 0) AS NUMERIC(24,
                                                              10)), @dig_total) , --SaleMoney
                                1 ,
                                b.PHRows ,
                                @VchCode
                        FROM    dbo.tpx_ReplenishList a
                                INNER JOIN bakdly b ON a.Ptypeid = b.Ptypeid
                                                       AND b.Vchcode = @VchCode
                                                       AND a.ColorID = B.ColorID
                                                       AND a.Comment = b.Comment
                                INNER JOIN dlyndx d ON b.vchcode=d.vchcode
                                LEFT JOIN Goodsstocks g ON d.ktypeid2 = g.KtypeId
                                                           AND b.PtypeId = g.PtypeId
                        WHERE   CHARINDEX(':' + a.ZBKeyId + ':', @tmpCodeStr) > 0
                        GROUP BY a.ptypeid ,
                                a.ColorID ,
                                a.SizeID ,
                                b.DlyOrder ,
                                g.price ,
                                a.Comment ,
                                b.PHRows
                IF @@ROWCOUNT <= 0 
                    GOTO error       
	            
                UPDATE  bakdly
                SET     total = b.total ,
                        TaxTotal = b.TaxTotal ,
                        Tax_Total = b.Tax_Total ,
                        BargainTotal = b.BargainTotal ,
                        [Convert] = b.[Convert] ,
                        DiscountTotal = b.DiscountTotal ,
                        SaleMoney = b.SaleMoney ,
                        price = CASE WHEN a.qty = 0 THEN 0
                                     ELSE ROUND(b.total / a.qty, @dig_price)
                                END
                FROM    bakdly a ,
                        ( SELECT    DlyOrder ,
                                    SUM(total) AS total ,
                                    SUM(TaxTotal) AS TaxTotal ,
                                    SUM(Tax_Total) AS Tax_Total ,
                                    SUM(BargainTotal) AS BargainTotal ,
                                    SUM([Convert]) AS [Convert] ,
                                    SUM(DiscountTotal) AS DiscountTotal ,
                                    SUM(SaleMoney) AS SaleMoney
                          FROM      bakdlydetail
                          GROUP BY  DlyOrder
                        ) AS b
                WHERE   a.vchcode = @VchCode
                        AND a.dlyorder = b.dlyorder 
                IF @@ROWCOUNT <= 0 
                    GOTO error  
                UPDATE  dbo.DlyNdx
                SET     qty = b.qty ,
                        total = b.total ,
                        checkdate = GETDATE() ,
                        VerifyFlow = CASE WHEN @CheckAndAccept = 0
                                               AND @vchtype = 218 THEN 0
                                          ELSE 1
                                     END ,
                        branchid2 = CASE WHEN @vchtype = 17 THEN ''
                                         ELSE branchid2
                                    END
                FROM    dlyndx a ,
                        ( SELECT    Vchcode ,
                                    SUM(qty) AS qty ,
                                    SUM(SaleMoney) AS total
                          FROM      bakdly
                          WHERE     UsedType = 1
                                    AND vchcode = @VchCode
                          GROUP BY  Vchcode
                        ) AS b
                WHERE   a.Vchcode = b.Vchcode
                        AND a.Vchcode = @VchCode
                IF @@ROWCOUNT <= 0 
                    GOTO error  
            END

        UPDATE  dbo.tpx_SaleIndex
        SET     draft = 1
        WHERE   JTypeId = @ABranchid
                AND CHARINDEX(':' + keyid + ':', @BillCode) > 0  
        GOTO sucess
    END TRY
    BEGIN CATCH
        PRINT ERROR_MESSAGE()
        GOTO Error
    END CATCH
    sucess:
    BEGIN
    --判断系统配置是否要用单据自动连续编号  
        DECLARE @orderid INT ,
            @stats INT
        SET @orderid = 13  
        SET @stats = 0  
        EXEC FZBS_FZGetSysCon @orderid, @stats OUTPUT  
        IF @stats = 1 
            BEGIN  
                --SELECT TOP 1
                --        @BillDate = SaleDate
                --FROM    dbo.tpx_SaleIndex a
                --WHERE   CHARINDEX(':' + keyid + ':', @BillCode) > 0    
                EXEC FZBS_FZModifyVchnumber @vchtype, @BillDate  
            END  
	--处理虚拟库存
        IF EXISTS ( SELECT TOP 1
                            vchcode
                    FROM    dlyndx
                    WHERE   vchcode = @VchCode ) 
            BEGIN
                DECLARE @nRetVirtual INT
                EXEC @nRetVirtual= FZModifyVirtualGoods 'BakDly', '', @VchCode,
                    1 --  smallint
                IF @nRetVirtual < 0 
                    BEGIN
                        GOTO error
                    END
		
            END
        COMMIT TRAN
        RETURN 0
    END
    Error:
    BEGIN
        ROLLBACK TRAN
        RETURN -1
    END
    Error1:
    BEGIN
        ROLLBACK TRAN
        RETURN -2
    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].[FZQueryRetailSale_BS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FZQueryRetailSale_BS]
GO




CREATE PROCEDURE FZQueryRetailSale_BS
    (
      @szPtypeId VARCHAR(50),
      @szKtypeid VARCHAR(2000),
      @szBtypeid VARCHAR(50),
      @szBeginData VARCHAR(50),
      @szEndData VARCHAR(50),
      @ifstop VARCHAR(2),
      @SaleTraitName VARCHAR(1000),
      @branchid VARCHAR(2000),
      @OperatorId VARCHAR(50) = '',
      @ifxiaopiao VARCHAR(2),  --是否包含未过账小票（1：是，0：否）
      @ifdraft VARCHAR(2)      --是否包含零售单草稿（1：是，0：否）
    )
AS 

--设置变量用于操作员拥有所有多级权限时，优化查询
DECLARE @PowerRangeP BIT --商品
DECLARE @PowerRangeE BIT --职员
DECLARE @PowerRangeA BIT --科目
DECLARE @PowerRangeB BIT --客户
DECLARE @PowerRangeC BIT --机构
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 0 AND TypeID = '00000') SET @PowerRangeP = 1 ELSE SET @PowerRangeP = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 1 AND TypeID = '00000') SET @PowerRangeE = 1 ELSE SET @PowerRangeE = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 3 AND TypeID = '00000') SET @PowerRangeA = 1 ELSE SET @PowerRangeA = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 4 AND TypeID = '00000') SET @PowerRangeB = 1 ELSE SET @PowerRangeB = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 5 AND TypeID = '00000') SET @PowerRangeC = 1 ELSE SET @PowerRangeC = 0

DECLARE @PStop BIT  
IF @ifstop = '0' SELECT @PStop = 0  
ELSE SELECT @PStop = 1

    DECLARE @szparid VARCHAR(50)  
    SET nocount ON  

    IF @branchid IS NULL 
        SET @branchid = ''  

    IF @szPtypeId IS NULL
        OR @szPtypeId = '' 
        SET @szparid = '00000'  
    ELSE 
        SET @szparid = @szPtypeId  

    IF @szPtypeId IS NULL 
        SET @szPtypeId = '' 

IF OBJECT_ID('tempdb..#FilterB','U') IS NOT NULL   
DROP TABLE #FilterB  
IF OBJECT_ID('tempdb..#FilterE','U') IS NOT NULL   
DROP TABLE #FilterE  
IF OBJECT_ID('tempdb..#FilterP','U') IS NOT NULL   
DROP TABLE #FilterP  
IF OBJECT_ID('tempdb..#FilterK','U') IS NOT NULL   
DROP TABLE #FilterK  
CREATE TABLE #FilterB (TypeId VARCHAR(50))    
CREATE TABLE #FilterE (TypeId VARCHAR(50))    
CREATE TABLE #FilterP (TypeId VARCHAR(50),PORDER INT)
CREATE TABLE #FilterK (KtypeId VARCHAR(50))      
INSERT  #FilterB(TypeId) SELECT  TypeId FROM  FN_GetPowerRangeBList(@OperatorId, @szBtypeid, '2,3,4,6')     
INSERT  #FilterE(TypeId) SELECT  TypeId FROM  FN_GetPowerRangeEList(@OperatorId, '')     
--INSERT  #FilterP(TypeId) SELECT  TypeId FROM  FN_GetPowerRangePList(@OperatorId, @szPtypeId) P WHERE (@PStop = 1 OR Stop = 0)
INSERT  #FilterP(TypeId,PORDER) 
SELECT    [typeid], porder
                          FROM      FN_GetPowerRangePTree(@OperatorId, @szPtypeId)  
                          WHERE     
                          deleted = 0 
                          AND [typeid] <> '00000' 
                          AND (@PStop = 1 OR Stop = 0) 
                          AND ( [parid] = @szparid OR ( typeid = @szPtypeId AND sonnum = 0 )) 
IF OBJECT_ID('tempdb..#tempPList','U') IS NOT NULL   
	DROP TABLE #tempPList  
SELECT TypeID,RetailPrice INTO #tempPList FROM dbo.FN_GetPowerRangePList('00000','00000') WHERE @PStop = 1 OR Stop = 0


INSERT  #FilterK(KtypeId) SELECT  KtypeId FROM  FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) 

    --IF OBJECT_ID('tempdb..#table_P') IS NOT NULL 
    --    DROP TABLE #table_P  

    IF @SaleTraitName = '全部' 
        SET @SaleTraitName = ''   
        
DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
--select @dig_qty  ,@dig_price ,@dig_total  ,@dig_dis  ,@dig_tax  ,@dig_rate 

IF OBJECT_ID('tempdb..#table_S') IS NOT NULL 
   DROP TABLE #table_S 
CREATE TABLE #table_S   --创建临时表
(
ptypeid VARCHAR(50),
Qty  numeric(24,10),
S_Tax_total  numeric(24,10),
TQty  numeric(24,10),
T_Tax_total  numeric(24,10),
Taxtotal  numeric(24,10),
SaleMoney  numeric(24,10),
tax_total  numeric(24,10),
vchtype int
)


INSERT INTO #table_S    --统计过账零售单
    Select	s.ptypeid,
			ds.[qty]      		AS Qty, 	
			ds.[tax_total]  	As S_Tax_total,  
			ds.[qty]		    AS TQty,   		
			ds.[tax_total]		AS T_Tax_total, 	
			ds.[taxtotal] 		AS Taxtotal,			
			ds.[salemoney]   	AS SaleMoney,
			ds.[tax_total]   	AS tax_total,
            s.vchtype
    FROM    DlyData s, dlydatadetail ds
    WHERE   S.[date] BETWEEN @szBeginData AND @szEndData
			AND s.vchtype IN ( 12, 100)
    	    AND s.redold = 'F'  
            AND s.dlyorder = ds.dlyorder           
            and ((1=@PowerRangeB AND s.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where s.BtypeId = FilterB.TypeId))  
            and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where s.EtypeId = FilterE.TypeId))  
            and exists(select 1  from #FilterK FilterK where s.ktypeId = Filterk.KtypeId)  	
            AND ( CustValue1 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue2 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue3 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue4 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue5 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue6 LIKE '%' + @SaleTraitName + '%'
                )

IF  @ifdraft=1  --统计包含零售单草稿	
BEGIN 
INSERT INTO #table_S
            Select	b.Ptypeid,
			-bd.[qty]      		AS Qty, 	
			-bd.[tax_total]  	As S_Tax_total,  
			-bd.[qty]		    AS TQty,   		
			-bd.[tax_total]		AS T_Tax_total, 	
			-bd.[taxtotal] 		AS Taxtotal,			
			-bd.[salemoney]   	AS SaleMoney,
			-bd.[tax_total]   	AS tax_total,
            b.vchtype
    FROM    Bakdly b INNER JOIN BakDlyDetail bd ON b.dlyorder = bd.dlyorder          
    WHERE   b.[date] BETWEEN @szBeginData AND @szEndData 
	    AND b.vchtype IN ( 12, 100)
        and ((1=@PowerRangeB AND b.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where b.BtypeId = FilterB.TypeId))  
        and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where b.EtypeId = FilterE.TypeId))  
        and exists(select 1  from #FilterK FilterK where b.ktypeId = Filterk.KtypeId)
        AND ( CustValue1 LIKE '%' + @SaleTraitName + '%'
              OR CustValue2 LIKE '%' + @SaleTraitName + '%'
              OR CustValue3 LIKE '%' + @SaleTraitName + '%'
              OR CustValue4 LIKE '%' + @SaleTraitName + '%'
              OR CustValue5 LIKE '%' + @SaleTraitName + '%'
              OR CustValue6 LIKE '%' + @SaleTraitName + '%'
            )
       AND EXISTS(SELECT 1 FROM dbo.DlyNdx x WHERE x.Vchcode = b.Vchcode AND x.Draft IN (1,4,10))    
END

IF  @ifxiaopiao=1 AND @SaleTraitName = '' --统计包含未过账小票
BEGIN

INSERT INTO #table_S
            Select	
             PSL.Ptypeid,
			-SUM(PSL.[qty])  AS Qty, 	
			-SUM(PSL.[Total])  As S_Tax_total,  
			-SUM(PSL.[qty])	AS TQty,   		
			-SUM(PSL.[Total])	AS T_Tax_total, 	
			            0    AS Taxtotal,			
			-SUM(PSL.[Total])  AS SaleMoney,
			-SUM(PSL.[Total])  AS tax_total,
            vchtype=12						 --POS过账后默认为零售单
    FROM    dbo.tpx_SaleList PSL,dbo.tpx_SaleIndex PSI
    WHERE   PSI.[Saledate] BETWEEN @szBeginData AND @szEndData
	        AND PSL.Ptypeid<>''
            AND PSL.ZBKeyId=PSI.keyId           
            and ((1=@PowerRangeB AND PSI.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where PSI.BtypeId = FilterB.TypeId))  
            and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where PSI.Salesman = FilterE.TypeId))  
            and exists(select 1  from #FilterK FilterK where PSI.ktypeId = Filterk.KtypeId) 	
            AND PSI.Draft=0 --Draft 结存标志[0-POS小票,1-草稿] 
            GROUP BY PSL.Ptypeid,PSL.[qty],PSL.[Total], PSL.retailprice
END




    SELECT  p.[typeid] AS ptypeid,
            SUM(qty) AS qty,                                          --销售数量
            SUM(Tqty) AS Tqty,                                        --退货数量
            SUM(qty) - SUM(Tqty) AS Sqty,                             --实际销售数量
            SUM(S_Tax_total) AS S_Tax_total,                          --实际销售含税金额
            SUM(T_Tax_total) AS T_Tax_total,                          --退货含税金额
            SUM(S_Tax_total) - SUM(T_Tax_total) AS SX_Tax_total,      --实际销售含税金额
            SUM(taxtotal) AS taxtotal,                                --税额
            SUM(RetailTotal) AS RetailTotal,						  --零售金额
            SUM(SaleMoney) AS SaleMoney,                              --实际销售金额
            SUM(tax_total) AS tax_total,                              --含税金额
            SUM(SaleMoney) - SUM(tax_total) AS DeductTotal            --抽成额          
    FROM    ( SELECT    p.[typeid],
                        p.porder,
                        [Qty],
                        [S_Tax_total],
                        [tqty],
                        [T_Tax_total],
                        [taxtotal],
                        [salemoney],
                        [tax_total],
                        RetailTotal
              FROM      #FilterP p
                        LEFT JOIN ( SELECT  SUBSTRING(ptypeid, 1, LEN(@szptypeid) + 5) AS ptypeid,
                                            -SUM(qty) AS qty,
                                            -SUM(S_Tax_total) AS S_Tax_total,
                                            SUM(tqty) AS tqty,
                                            SUM(T_Tax_total) AS T_Tax_total,
                                            -SUM(taxtotal) AS taxtotal,
                                            -SUM(salemoney) AS SaleMoney,
                                            -SUM(tax_total) AS tax_total,
                                            ROUND(CAST((SUM(-qty) - SUM(tqty)) AS NUMERIC(24,10))*CAST(RetailPrice AS NUMERIC(24,10)),@dig_total) RetailTotal
                                    FROM    (  
											SELECT  Ptypeid,
													SUM(ISNULL(s.[qty], 0)) AS Qty, 				--销售数量
													SUM(ISNULL(s.[tax_total], 0)) AS S_Tax_total,  	--价税合计（销售）
													0 AS TQty,   									--退货数量
													0 AS T_Tax_total, 								--价税合计（退货）
													SUM(ISNULL(s.[taxtotal], 0)) AS Taxtotal,		--税额
													SUM(ISNULL(s.[salemoney], 0)) AS SaleMoney,
													SUM(ISNULL(s.[tax_total], 0)) AS tax_total
											FROM     #table_S S
											WHERE    qty < 0
											GROUP BY ptypeid, vchtype
											
											UNION ALL
											
											SELECT  Ptypeid,
													0 AS Qty, 										--销售数量
													0 AS S_Tax_total,  								--价税合计（销售）
													SUM(ISNULL(s.[qty], 0)) AS TQty,   				--退货数量
													SUM(ISNULL(s.[tax_total], 0)) AS T_Tax_total, 	--价税合计（退货）
													SUM(ISNULL(s.[taxtotal], 0)) AS Taxtotal,		--税额
													SUM(ISNULL(s.[salemoney], 0)) AS SaleMoney,
													SUM(ISNULL(s.[tax_total], 0)) AS tax_total
											FROM      #table_S S
											WHERE     qty > 0
											GROUP BY  ptypeid, vchtype
											) C
											INNER JOIN #tempPList D ON D.typeid = C.ptypeid
									 GROUP BY SUBSTRING(ptypeid, 1, LEN(@szptypeid) + 5),RetailPrice
                           ) Salebill ON p.[typeid] = Salebill.ptypeid
	            ) P
	    GROUP BY p.porder,[typeid]
    ORDER BY p.porder,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].[FN_SaleBillDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FN_SaleBillDetail]
GO
/*
  作者:QF
  时间:2011-08-30			
  主要内容:功能增加 发货类型、退货类型

*/


CREATE Proc FN_SaleBillDetail
( 
	@mode	   varchar(50),
	@startdate varchar(10),  
 	@enddate   varchar(10),  
	@ptypeid   varchar(8000),
	@btypeid   varchar(50),
	@etypeid   varchar(50),
	@ktypeid   varchar(2000),
	@branchid  varchar(2000),
	@OperatorId varchar(50),
	@dtypeid    varchar(50)='',
	@SaleTraitname  varchar(1000)='',
	@vchtype    varchar(100)='',
	@pricetype      TINYINT=0,
	@IsStop BIT = 1  ,
        @ifxiaopiao       VARCHAR(2),     --是否包含未过账小票（1：是，0：否）
        @ifdraft          VARCHAR(2),      --是否包含零售单草稿（1：是，0：否）
	@OpID		INT = 0   --0-全部 , 其他为具体类型 
)
AS

if @SaleTraitname='全部' set @SaleTraitname=''  

--总部和加盟商共用一个，当不进行筛选单据的情况下，要把单据范围补齐  
IF LEFT(@branchid,5)='00001'  
BEGIN  
 IF @vchtype is null or @vchtype=''  
     SET @vchtype='100,11,45,24,12,222,224' --总部统计的销售主体单据  
END  
ELSE  
BEGIN  
 IF @vchtype is null or @vchtype=''  
     SET @vchtype='11,12,45,24'   --加盟商统计的销售主体单据  
END 

	IF object_id('tempdb..#P') is not null  
		drop table #P
	IF object_id('tempdb..#b') is not null  
		drop table #b
	IF object_id('tempdb..#e') is not null  
		drop table #e
	IF object_id('tempdb..#br') is not null  
		drop table #br
	SELECT TypeId,[stop] INTO #P FROM  FN_GetPowerRangePList(@OperatorId, @ptypeid)
	SELECT Typeid INTO #b FROM  FN_GetPowerRangeBList(@OperatorId, @btypeid, '2,3,4,6')
	SELECT Typeid INTO #e FROM  FN_GetPowerRangeEList(@OperatorId, @EtypeID)
	SELECT KtypeId,selfhelp INTO #br FROM  FN_GetStockListOfBranch(@OperatorID, @BranchId, @ktypeid)

	CREATE CLUSTERED INDEX I_p_typeid ON #P(TypeId)
	CREATE CLUSTERED INDEX I_e_typeid ON #e(TypeId)
	CREATE CLUSTERED INDEX I_b_typeid ON #b(TypeId)
	CREATE CLUSTERED INDEX I_br_typeid ON #br(KtypeId)
		

if @Mode='S_SPPHB' --商品排行榜明细
BEGIN
	Select a.[vchcode], a.[vchtype],a.ktypeid,a.ptypeid,a.btypeid,  
	sum(ABS((case when isnull(ad.[qty], 0) > 0 then isnull(ad.[qty], 0) else 0 end))) AS InStock,  
	sum(ABS((case when isnull(ad.[qty], 0) < 0 then isnull(ad.[qty], 0) else 0 end))) AS OutStock,  
	-sum(isnull(ad.[tax_total], 0)) as Total, a.[date],SUM(ad.qty) as cccc,a.RedOld,a.RedWord  
	From  Dlydata a 
	INNER JOIN #P p ON  a.ptypeid=p.typeid  	
	INNER JOIN dlydatadetail ad   ON  a.dlyorder =ad.dlyorder  
	
	Where @startdate<=[date]  and @enddate>=[date] 
	and Left(a.ptypeid, Len(@ptypeid+'%')) like  @ptypeid+'%'  
	and a.usedtype=case when vchtype in(222,224) then 1 else a.usedtype end  
		
	and exists(select 1  from #b FilterB  where a.BtypeId = FilterB.TypeId)    
	and exists(select 1  from #e FilterE  where a.EtypeId = FilterE.TypeId)    
	and exists(select 1  from #br FilterK where a.ktypeId = Filterk.KtypeId)       
	and exists(select 1  from FN_GetPowerRangeVList(@BranchId) FilterV where a.vchtype=FilterV.vchtype)             
	
	Group by a.vchcode,vchtype,[date],a.ktypeid,a.ptypeid,a.btypeid,a.RedOld,a.RedWord  
	order by a.vchcode  
END

IF @Mode='S_xzzk' --销售状况表明细
BEGIN
	Select a.[vchcode], a.[vchtype],a.ktypeid,a.ptypeid,a.btypeid,  
	sum(ABS((case when isnull(ad.[qty], 0) > 0 then isnull(ad.[qty], 0) else 0 end))) AS InStock,  
	sum(ABS((case when isnull(ad.[qty], 0) < 0 then isnull(ad.[qty], 0) else 0 end))) AS OutStock,  
	-sum(isnull(ad.[tax_total], 0)) as Total, a.[date],SUM(ad.qty) as cccc,a.RedOld,a.RedWord  
	From  --Dlydata a
	(
		SELECT * FROM Dlydata where price>0 and @pricetype=1 
		Union all 
		SELECT * FROM Dlydata where @pricetype=0
		Union all
		SELECT * FROM Dlydata where price=0 and @pricetype=2
	)a 
	INNER JOIN #P p ON  a.ptypeid=p.typeid  	
	INNER JOIN dlydatadetail ad   ON  a.dlyorder =ad.dlyorder  
	
	Where @startdate<=[date]  and @enddate>=[date] 
	AND p.[stop] IN (CASE stop WHEN 1 THEN @IsStop ELSE 0 END)
	AND a.OpId = (CASE WHEN @OpID=0 THEN a.OpId ELSE @OpID END )
	--and Left(a.ptypeid, Len(@ptypeid+'%')) like  @ptypeid+'%'  
	and a.usedtype=case when vchtype in(222,224) then 1 else a.usedtype end  
	and (
		     CustValue1 like '%'+@SaleTraitName+'%'    
		     or CustValue2 like '%'+@SaleTraitName+'%'  
		     or CustValue3 like '%'+@SaleTraitName+'%'  
		     or CustValue4 like '%'+@SaleTraitName+'%'  
		     or CustValue5 like '%'+@SaleTraitName+'%'  
		     or CustValue6 like '%'+@SaleTraitName+'%'  
	     )  	
	and  dtypeid like @dtypeid+'%' 
	and exists(select 1  from #b FilterB  where a.BtypeId = FilterB.TypeId)    
	and exists(select 1  from #e FilterE  where a.EtypeId = FilterE.TypeId)    
	and exists(select 1  from #br FilterK where a.ktypeId = Filterk.KtypeId)       
	and exists(select 1  from FN_GetPowerRangeVList(@BranchId) FilterV where a.vchtype=FilterV.vchtype)             
	
	Group by a.vchcode,vchtype,[date],a.ktypeid,a.ptypeid,a.btypeid,a.RedOld,a.RedWord  
	order by a.vchcode  
END

IF @Mode='S_spxsfx' --商品销售分析表明细
BEGIN
	Select a.[vchcode], a.[vchtype],a.ktypeid,a.ptypeid,a.btypeid,  
	sum(ABS((case when isnull(ad.[qty], 0) > 0 then isnull(ad.[qty], 0) else 0 end))) AS InStock,  
	sum(ABS((case when isnull(ad.[qty], 0) < 0 then isnull(ad.[qty], 0) else 0 end))) AS OutStock,  
	-sum(isnull(ad.[tax_total], 0)) as Total, a.[date],SUM(ad.qty) as cccc,a.RedOld,a.RedWord  
	From  Dlydata a 
	INNER JOIN #P p ON  a.ptypeid=p.typeid  	
	INNER JOIN dlydatadetail ad   ON  a.dlyorder =ad.dlyorder  
	
	Where @startdate<=[date]  and @enddate>=[date] 
	AND a.OpId = (CASE WHEN @OpID=0 THEN a.OpId ELSE @OpID END )
	and Left(a.ptypeid, Len(@ptypeid+'%')) like  @ptypeid+'%'  
	and a.usedtype=case when vchtype in(222,224) then 1 else a.usedtype end  
	and (
		     CustValue1 like '%'+@SaleTraitName+'%'    
		     or CustValue2 like '%'+@SaleTraitName+'%'  
		     or CustValue3 like '%'+@SaleTraitName+'%'  
		     or CustValue4 like '%'+@SaleTraitName+'%'  
		     or CustValue5 like '%'+@SaleTraitName+'%'  
		     or CustValue6 like '%'+@SaleTraitName+'%'  
	     )  	
	and  dtypeid like @dtypeid+'%' 
	and exists(select 1  from #b FilterB  where a.BtypeId = FilterB.TypeId)    
	and exists(select 1  from #e FilterE  where a.EtypeId = FilterE.TypeId)    
	and exists(select 1  from #br FilterK where a.ktypeId = Filterk.KtypeId)       
	and exists(select 1  from FN_GetPowerRangeVList(@BranchId) FilterV where a.vchtype=FilterV.vchtype)             
	and exists(select GetID FROM FN_GetIdStrListTable(@vchtype) FilterVch WHERE a.vchtype=FilterVch.GetID)  --单据类型
	AND p.Stop IN (CASE @IsStop WHEN 1 THEN p.stop ELSE @IsStop END)--是否包含停用商品
	Group by a.vchcode,vchtype,[date],a.ktypeid,a.ptypeid,a.btypeid,a.RedOld,a.RedWord  
	order by a.vchcode  
END

IF @Mode='S_khxsfx' --客户销售分析表明细
BEGIN
	Select ds.[vchcode], ds.[vchtype],   
	sum(ABS((case when isnull(dsd.[qty], 0) > 0 then isnull(dsd.[qty], 0) else 0 end))) AS InStock,  
	sum(ABS((case when isnull(dsd.[qty], 0) < 0 then isnull(dsd.[qty], 0) else 0 end))) AS OutStock,  
	-sum((isnull((dsd.[tax_total]), 0))) as Total, ds.[date],isnull(d.[number], '''') as [number],   
	ds.redold,isnull(d.[summary], '''') as comment,Ptypeid,ds.btypeid,ds.Ktypeid,ds.RedWord  
	from Dlydata ds   
	left join dlyndx d on ds.vchcode=d.vchcode  
	left join dlydatadetail dsd on ds.dlyorder = dsd.dlyorder  
	where  ds.[date] between @startdate and @enddate
	AND ds.OpId=CASE WHEN @OpID = 0 THEN ds.Opid ELSE @OpID END
	and ds.usedtype=case when ds.vchtype in(222,224) then 1 else ds.usedtype end  
	and  ds.dtypeid like @dtypeid+'%' 
	and exists(select 1  from #P FilterP  where ds.PtypeId = FilterP.TypeId)    
	and exists(select 1  from #b FilterB  where ds.BtypeId = FilterB.TypeId)    
	and exists(select 1  from #e FilterE  where ds.EtypeId = FilterE.TypeId)    
	and exists(select 1  from #br FilterK where ds.ktypeId = Filterk.KtypeId)       
	and exists(select 1  from FN_GetPowerRangeVList(@BranchId) FilterV where ds.vchtype=FilterV.vchtype)             
	group by ds.vchcode,ds.vchtype,ds.[date],d.number,ds.redold,d.summary,Ptypeid,ds.btypeid,ds.Ktypeid,ds.RedWord  
END

IF @mode='S_khyw'--客户业务统计明细
BEGIN	
	Select v.*,atypeid 
	From
	(   
	    select a.vchcode, a.vchtype, a.atypeid, a.date,  
	     b.redold, a.btypeid, b.number, b.summary as comment,  
	     a.total,  
	     case when a.total > 0 then a.total else 0 end as increase,  
	     case when a.total < 0 then -1*a.total else 0 end as reduce,-(a.Total) as ReverseTotal,  
	     a.redword,b.BranchId  
	     from 
	     dlyndx b inner join dlya a  on b.vchcode = a.vchcode 
	     left join btype c  on a.btypeid = c.typeid	      
	    where @startdate<=b.[date] and @enddate>=b.[date]  	   
	    	and a.atypeid ='0000100005' 		       
	    	and b.vchtype in(100,101,11,45,26,24,13,12,222,224,4,36,93,115,66)  	    
	    	and exists(select 1  from #b FilterB  where a.BtypeId = FilterB.TypeId)      --权限  
		and exists(SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorId,@BranchId) FilterVC where a.branchid = FilterVC.branchid)      --权限
	    UNION ALL     
	      
	    select a.vchcode, a.vchtype, a.atypeid, a.date,   
	     b.redold, a.btypeid, b.number, b.summary as comment,  
	     -1*a.total total,  
	     case when a.total < 0 then -1*a.total else 0 end as increase,  
	     case when a.total > 0 then a.total else 0 end as reduce,a.total as ReverseTotal,  
	     a.redword,b.BranchId  
	    from dlyndx b inner join dlya a on b.vchcode = a.vchcode  
	     		  left join btype c on a.btypeid = c.typeid       
	    where @startdate<=b.[date] and @enddate>=b.[date]  
	    	and b.vchtype in(100,101,11,45,26,24,13,12,222,224,4,36,93,115,66)  	    
	    	and a.atypeid='0000200001'  	      
	    	and exists(select 1  from #b FilterB  where a.BtypeId = FilterB.TypeId)      --权限	
		and exists(SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorId,@BranchId) FilterVC where a.branchid = FilterVC.branchid)      --权限
	    UNION ALL  
	    select distinct a.vchcode, a.vchtype, ''as atypeid, a.date,   
	         b.redold, a.btypeid, b.number, b.summary as comment,    
	        0 as total,    
	        0 as increase,    
	        0 as reduce,0 as ReverseTotal,a.redword,b.BranchId    
	        from dlyndx b inner join   
	     	(
			Select distinct btypeid,vchcode,vchtype,[date],redword from dlya   
	      		where vchcode not in (Select vchcode from dlya where atypeid ='0000100005' or atypeid='0000200001')
	     	)a on b.vchcode = a.vchcode           
	        left join btype c on a.btypeid = c.typeid               
	        where @startdate<=b.[date] and @enddate>=b.[date]    
	     	and b.vchtype in(100,101,11,45,26,24,13,12,222,224,4,36,93,115,66)  	        
		and exists(select 1  from #b FilterB  where a.BtypeId = FilterB.TypeId)      --权限   
		and exists(SELECT 1 FROM  FN_GetPowerRangeBCList(@OperatorId,@BranchId) FilterVC where b.branchid = FilterVC.branchid)      --权限
	) v 
	left join atype aa  
	on v.atypeid = aa.typeid and v.BranchId = aa.BranchId   
	WHERE v.Increase <> 0 OR Reduce <> 0	--应收增加为0 且 应收减少为0 即不显示  
	order by v.vchcode 
END

IF @mode='lsxstj'--零售销售统计明细
BEGIN

	IF OBJECT_ID('tempdb..#temp_data') IS NOT NULL 
	   DROP TABLE #temp_data 
	CREATE TABLE #temp_data   --创建临时表
	(
        vchcode  int,
        vchtype  int,
		InStock  numeric(24,10),
		OutStock numeric(24,10),
		Total    numeric(24,10),
        [date]   varchar(20),
        [number] varchar(50),
        comment  varchar(500),
        ptypeid  varchar(50),
        btypeid  varchar(50),
        ktypeid  varchar(50),
        redold   char(1),
        RedWord  char(1),
        Draft	 INT
	)
	
        INSERT INTO #temp_data
	Select ds.[vchcode], ds.[vchtype],   
	sum(ABS((case when isnull(dsd.[qty], 0) > 0 then isnull(dsd.[qty], 0) else 0 end))) AS InStock,  
	sum(ABS((case when isnull(dsd.[qty], 0) < 0 then isnull(dsd.[qty], 0) else 0 end))) AS OutStock,  
	-sum((isnull((dsd.[tax_total]), 0))) as Total, 
        ds.[date], 
        isnull(d.[number],'''') as [number],  
	isnull(d.[summary], '''') as comment,Ptypeid,ds.btypeid,ds.Ktypeid,ds.redold,ds.RedWord,d.Draft  
	from Dlydata ds   
	left join Btype b  on ds.Btypeid =b.typeid  
	left join dlyndx d on ds.vchcode=d.vchcode   
	left join ptype p on ds.ptypeid=p.typeid  
	left join dlydatadetail dsd on ds.dlyorder = dsd.dlyorder  
	where  ds.vchtype in(12,13,100,101)   
	and ds.[date] between @startdate and @enddate  			
	and (
		        CustValue1 like '%'+@SaleTraitName+'%'    
		     or CustValue2 like '%'+@SaleTraitName+'%'  
		     or CustValue3 like '%'+@SaleTraitName+'%'  
		     or CustValue4 like '%'+@SaleTraitName+'%'  
		     or CustValue5 like '%'+@SaleTraitName+'%'  
		     or CustValue6 like '%'+@SaleTraitName+'%'  
	     )  		

	AND p.Stop IN (CASE @IsStop WHEN 1 THEN p.stop ELSE @IsStop END)--是否包含停用商品     	
	group by ds.vchcode,ds.vchtype,ds.[date],d.number,d.summary,Ptypeid,ds.btypeid,ds.Ktypeid,ds.redold,ds.RedWord,d.Draft  


	IF  @ifdraft=1  --统计包含零售单草稿
	BEGIN 
	INSERT INTO #temp_data
				Select	    
									b.vchcode,
						b.vchtype, 
				sum(ABS((case when isnull(bd.[qty], 0) < 0 then isnull(bd.[qty], 0) else 0 end))) AS InStock, 
				sum(ABS((case when isnull(bd.[qty], 0) > 0 then isnull(bd.[qty], 0) else 0 end))) AS OutStock, 
				sum((isnull((bd.[tax_total]), 0))) as Total,    
						b.[date],
					   [number]=' ',
						comment=' ',
						b.ptypeid,
						b.btypeid,
						b.ktypeid,
						redold='F',
						RedWord='F',d.Draft
			 FROM    Bakdly b, BakDlyDetail bd LEFT JOIN dlyndx d ON d.Vchcode = bd.Vchcode 
		where  b.vchtype in(12,13,100,101)   
		AND B.DlyOrder = BD.DlyOrder  
		and b.[date] between @startdate and @enddate  			
		and (
					CustValue1 like '%'+@SaleTraitName+'%'    
				 or CustValue2 like '%'+@SaleTraitName+'%'  
				 or CustValue3 like '%'+@SaleTraitName+'%'  
				 or CustValue4 like '%'+@SaleTraitName+'%'  
				 or CustValue5 like '%'+@SaleTraitName+'%'  
				 or CustValue6 like '%'+@SaleTraitName+'%'  
			 )
		AND d.Draft IN (1,4,10)	   		
		and exists(select 1  from #P FilterP  where b.PtypeId = FilterP.TypeId)    
		and exists(select 1  from #b FilterB  where b.BtypeId = FilterB.TypeId)
		and exists(select 1  from FN_GetPowerRangeEList(@OperatorId,'') FilterE  where b.EtypeId = FilterE.TypeId)      	
		and exists(select 1  from #br FilterK where b.ktypeId = Filterk.KtypeId) 	
		group by b.vchcode,b.vchtype,b.[date],b.Ptypeid,b.btypeid,b.Ktypeid,d.Draft 
	END

	IF  @ifxiaopiao=1 AND @SaleTraitName = '' --统计包含未过账小票
	BEGIN

	INSERT INTO #temp_data
				SELECT 0 as vchcode,CASE WHEN BtypeID LIKE '00003%' THEN 100 ELSE 12 END AS vchtype,	--未过账小票按机构分为代销零售单和零售单 
				sum(ABS((case when isnull(PSL.[qty], 0) < 0 then isnull(PSL.[qty], 0) else 0 end))) AS InStock, 
				sum(ABS((case when isnull(PSL.[qty], 0) > 0 then isnull(PSL.[qty], 0) else 0 end))) AS OutStock, 
					   PSL.[total] AS Total,    
					   CONVERT(VARCHAR,PSI.SaleDate,23) AS [date],
						[number]=' ',
						comment=' ',
						PSL.ptypeid,
						PSI.btypeid,
						PSI.ktypeid,
						redold='F',
						RedWord='F',psi.Draft  
		FROM    dbo.tpx_SaleList PSL,dbo.tpx_SaleIndex PSI
		WHERE   PSI.[Saledate] between @startdate and @enddate 
			AND PSL.Ptypeid<>''
				AND PSL.ZBKeyId=PSI.keyId           
			and exists(select 1  from #P FilterP  where PSL.PtypeId = FilterP.TypeId)    
		and exists(select 1  from #b FilterB  where PSI.BtypeId = FilterB.TypeId)
		and exists(select 1  from FN_GetPowerRangeEList(@OperatorId,'') FilterE  where PSI.Salesman = FilterE.TypeId)      	
		and exists(select 1  from #br FilterK where PSI.ktypeId = Filterk.KtypeId) 	
			AND PSI.Draft=0 --Draft 结存标志[0-POS小票,1-草稿] 
			group by PSL.[total], PSI.SaleDate,PSL.ptypeid,PSI.btypeid,PSI.ktypeid,psi.Draft
	END

	SELECT vchcode,VchType,InStock,OutStock,Total,[date],[number],comment,ptypeid,btypeid,ktypeid,redold,RedWord,Draft FROM #temp_data
	WHERE 1 = 1
	and exists(select 1  from #P FilterP  where #temp_data.PtypeId = FilterP.TypeId AND (@IsStop = 1 OR Stop = 0))
	and exists(select 1  from #b FilterB  where #temp_data.BtypeId = FilterB.TypeId)
	--and exists(select 1  from FN_GetPowerRangeEList(@OperatorId,'') FilterE  where #temp_data.EtypeId = FilterE.TypeId)      	
	and exists(select 1  from FN_GetStockListOfBranch(@OperatorID,@BranchId,@Ktypeid) FilterK where #temp_data.ktypeId = Filterk.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 1
           FROM   dbo.sysobjects
           WHERE  id = object_id(N'[dbo].[FZQueryRetailSaleListCS_BS]')
                  AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
  DROP PROCEDURE [dbo].[FZQueryRetailSaleListCS_BS]

GO

CREATE PROCEDURE FZQueryRetailSaleListCS_BS (
  @szPtypeId     VARCHAR(50),
  @szKtypeid     VARCHAR(2000),
  @szBtypeid     VARCHAR(50),
  @szBeginData   VARCHAR(50),
  @szEndData     VARCHAR(50),
  @ifstop        VARCHAR(2),
  @attrib1       INT =-1,
  @attrib2       INT =-1,
  @attrib3       INT =-1,
  @attrib4       INT =-1,
  @Assist1TypeID INT =-1,
  @Assist2TypeID INT =-1,
  @Assist3TypeID INT =-1,
  @Assist4TypeID INT =-1,
  @Sizeid        VARCHAR(4)='',
  @Colorid       VARCHAR(4)='',
  @SaleTraitName VARCHAR(1000),
  @branchid      VARCHAR(2000),
  @OperatorId    VARCHAR(50)='',
  @ifxiaopiao VARCHAR(2),  --是否包含未过账小票（1：是，0：否）
  @ifdraft VARCHAR(2)      --是否包含零售单草稿（1：是，0：否）
)
AS
       --设置变量用于操作员拥有所有多级权限时，优化查询
    DECLARE @PowerRangeP BIT --商品
    DECLARE @PowerRangeE BIT --职员
    DECLARE @PowerRangeA BIT --科目
    DECLARE @PowerRangeB BIT --客户
    DECLARE @PowerRangeC BIT --机构
    IF EXISTS (SELECT 1 FROM   UserPowerRange WHERE  EtypeID = @OperatorId AND BaseType = 0 AND TypeID = '00000') SET @PowerRangeP = 1 ELSE SET @PowerRangeP = 0
    IF EXISTS (SELECT 1 FROM   UserPowerRange WHERE  EtypeID = @OperatorId AND BaseType = 1 AND TypeID = '00000') SET @PowerRangeE = 1 ELSE SET @PowerRangeE = 0
    IF EXISTS (SELECT 1 FROM   UserPowerRange WHERE  EtypeID = @OperatorId AND BaseType = 3 AND TypeID = '00000') SET @PowerRangeA = 1 ELSE SET @PowerRangeA = 0
    IF EXISTS (SELECT 1 FROM   UserPowerRange WHERE  EtypeID = @OperatorId AND BaseType = 4 AND TypeID = '00000') SET @PowerRangeB = 1 ELSE SET @PowerRangeB = 0
    IF EXISTS (SELECT 1 FROM   UserPowerRange WHERE  EtypeID = @OperatorId AND BaseType = 5 AND TypeID = '00000') SET @PowerRangeC = 1 ELSE SET @PowerRangeC = 0

    DECLARE @tempPtypeid VARCHAR(50)
    SET @tempPtypeid=@szPtypeId
    IF @branchid IS NULL
      SET @branchid=''
    IF @szPtypeId IS NULL OR @szPtypeId = ''
      SET @szPtypeId='%'
    IF @Colorid IS NULL OR @Colorid = '' OR @Colorid = '0'
      SET @Colorid='%'
    IF @Sizeid IS NULL OR @Sizeid = '' OR @Sizeid = '0'
      SET @Sizeid='%'
      
IF OBJECT_ID('tempdb..#FilterB','U') IS NOT NULL   
DROP TABLE #FilterB  
IF OBJECT_ID('tempdb..#FilterE','U') IS NOT NULL   
DROP TABLE #FilterE  
--IF OBJECT_ID('tempdb..#FilterP','U') IS NOT NULL   
--DROP TABLE #FilterP  
IF OBJECT_ID('tempdb..#FilterK','U') IS NOT NULL   
DROP TABLE #FilterK  
CREATE TABLE #FilterB (TypeId VARCHAR(50))    
CREATE TABLE #FilterE (TypeId VARCHAR(50))    
--CREATE TABLE #FilterP (TypeId VARCHAR(50),PORDER INT)    
CREATE TABLE #FilterK (KtypeId VARCHAR(50))      
INSERT  #FilterB(TypeId) SELECT  TypeId FROM  FN_GetPowerRangeBList(@OperatorId, @szBtypeid, '2,3,4,6')     
INSERT  #FilterE(TypeId) SELECT  TypeId FROM  FN_GetPowerRangeEList(@OperatorId, '') 
INSERT  #FilterK(KtypeId) SELECT  KtypeId FROM  FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) 

--取小数位精度配置
DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output

    IF object_id('tempdb..#table_P') IS NOT NULL
      DROP TABLE #table_P

    IF object_id('tempdb..#tmp_data') IS NOT NULL
      DROP TABLE #tmp_data

    IF @SaleTraitName = '全部'
      SET @SaleTraitName=''

IF OBJECT_ID('tempdb..#tmp_data') IS NOT NULL 
   DROP TABLE #tmp_data
 
CREATE TABLE #tmp_data   --创建临时表
(
ptypeid VARCHAR(50),
Qty  numeric(24,10),
S_Tax_total  numeric(24,10),
TQty  numeric(24,10),
T_Tax_total  numeric(24,10),
Taxtotal  numeric(24,10),
SaleMoney  numeric(24,10),
tax_total  numeric(24,10),
colorid INT,
sizeid  INT,
vchtype INT
)

INSERT INTO #tmp_data
            Select	 Ptypeid,
           dd.[qty]       AS [Qty],
           dd.[Tax_total] AS S_Tax_total,
           dd.[qty]       AS [TQty],
           dd.[Tax_total] AS T_Tax_total,
           dd.[taxtotal]  AS Taxtotal,
           dd.[salemoney] AS SaleMoney,
           dd.[tax_total] AS Tax_total,
           dd.colorid,
           dd.sizeid ,
           s.Vchtype
    FROM   dlydata S,
           DlyDataDetail dd
    WHERE  s.vchtype IN(12, 100)
           AND s.[date] BETWEEN @szBeginData AND @szEndData
           AND s.dlyorder = dd.dlyorder
           AND s.billtype = 2
           AND s.redold = 'F'
           AND CAST(dd.sizeid AS VARCHAR(4)) LIKE @Sizeid
           AND CAST(dd.colorid AS VARCHAR(4)) LIKE @Colorid
           AND ((1 = @PowerRangeB
                 AND s.BtypeId LIKE @szBtypeid + '%')
                 OR EXISTS(SELECT 1
                           FROM   #FilterB FilterB
                           WHERE  s.BtypeId = FilterB.TypeId))
           AND ((1 = @PowerRangeE)
                 OR EXISTS(SELECT 1
                           FROM   #FilterE FilterE
                           WHERE  s.EtypeId = FilterE.TypeId))
           AND EXISTS(SELECT 1 FROM   #FilterK FilterK WHERE  s.ktypeId = Filterk.KtypeId)
           AND (CustValue1 LIKE '%' + @SaleTraitName + '%'
                 OR CustValue2 LIKE '%' + @SaleTraitName + '%'
                 OR CustValue3 LIKE '%' + @SaleTraitName + '%'
                 OR CustValue4 LIKE '%' + @SaleTraitName + '%'
                 OR CustValue5 LIKE '%' + @SaleTraitName + '%'
                 OR CustValue6 LIKE '%' + @SaleTraitName + '%')

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


IF  @ifdraft=1  --统计包含零售单草稿
BEGIN 
INSERT INTO #tmp_data
            Select	b.Ptypeid,
			-bd.[qty]      		AS Qty, 	
			-bd.[tax_total]  	As S_Tax_total,  
			-bd.[qty]		    AS TQty,   		
			-bd.[tax_total]		AS T_Tax_total, 	
			-bd.[taxtotal] 		AS Taxtotal,			
			-bd.[salemoney]   	AS SaleMoney,
			-bd.[tax_total]   	AS tax_total,
             bd.[colorid] ,
             bd.[sizeid],
             b.vchtype

    FROM    Bakdly b, BakDlyDetail bd
    WHERE   b.[date] BETWEEN @szBeginData AND @szEndData
	    AND b.vchtype IN ( 12, 100)
	    AND b.Ptypeid<>''
        AND b.dlyorder = bd.dlyorder           
        and ((1=@PowerRangeB AND b.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where b.BtypeId = FilterB.TypeId))  
        and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where b.EtypeId = FilterE.TypeId))  
        and exists(select 1  from #FilterK FilterK where b.ktypeId = Filterk.KtypeId) 	
        AND ( CustValue1 LIKE '%' + @SaleTraitName + '%'
              OR CustValue2 LIKE '%' + @SaleTraitName + '%'
              OR CustValue3 LIKE '%' + @SaleTraitName + '%'
              OR CustValue4 LIKE '%' + @SaleTraitName + '%'
              OR CustValue5 LIKE '%' + @SaleTraitName + '%'
              OR CustValue6 LIKE '%' + @SaleTraitName + '%'
            )
        AND EXISTS(SELECT 1 FROM dbo.DlyNdx x WHERE x.Vchcode = b.Vchcode AND x.Draft IN (1,4,10))
END

IF  @ifxiaopiao=1  AND @SaleTraitName = ''--统计包含未过账小票
BEGIN

INSERT INTO #tmp_data
            Select	
             PSL.Ptypeid,
			-SUM(PSL.[qty])  AS Qty, 	
			-SUM(PSL.[total])  As S_Tax_total,  
			-SUM(PSL.[qty])	AS TQty,   		
			-SUM(PSL.[total])	AS T_Tax_total, 	
			        0   AS Taxtotal,			
			-SUM(PSL.[total])  AS SaleMoney,
			-SUM(PSL.[total])  AS tax_total,
		         PSL.[colorid] ,
		         PSL.[sizeid],
		         vchtype=12 --POS过账后默认为零售单
    FROM    dbo.tpx_SaleList PSL,dbo.tpx_SaleIndex PSI
    WHERE   PSI.[Saledate] BETWEEN @szBeginData AND @szEndData
	        AND PSL.Ptypeid<>''
            AND PSL.ZBKeyId=PSI.keyId           
            and ((1=@PowerRangeB AND PSI.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where PSI.BtypeId = FilterB.TypeId))  
            and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where PSI.Salesman = FilterE.TypeId))  
            and exists(select 1  from #FilterK FilterK where PSI.ktypeId = Filterk.KtypeId)
            AND PSI.Draft=0 --Draft 结存标志[0-POS小票,1-草稿] 
            GROUP BY PSL.Ptypeid,PSL.[colorid],PSL.[SizeID]
       
END




    ------------------------------------------------------
    SELECT p.[typeid],
           p.porder,
           isnull([Qty], 0)       AS [Qty],
           isnull(S_Tax_total, 0) AS S_Tax_total,
           isnull(Tqty, 0)        AS Tqty,
           isnull(T_Tax_total, 0) AS T_Tax_total,
           isnull([SaleMoney], 0) AS [SaleMoney],
           isnull([taxtotal], 0)  AS Taxtotal,
           isnull([tax_total], 0) AS Tax_total,
           p.RetailPrice,
           p.sizeid,
           p.colorid
    INTO   #table_P
    FROM   (SELECT p1.[typeid],
                   c.sizeid,
                   b.colorid,
                   porder,
                   retailprice
            FROM   (SELECT p1.[typeid],
                           porder,
                           retailprice
                    FROM   FN_GetPowerRangePList(@OperatorId, @tempPtypeid) p1
                           LEFT JOIN (SELECT a.ptypeid,
                                             a.attributeid,
                                             b.typeid
                                      FROM   ptypeattribute a
                                             INNER JOIN assistattribute b
                                               ON a.attributeid = b.attributeid
                                      WHERE  typeid = @Assist1TypeID) ls1
                             ON @attrib1 <> -1
                                AND ls1.ptypeid = p1.typeid
                           LEFT JOIN (SELECT a.ptypeid,
                                             a.attributeid,
                                             b.typeid
                                      FROM   ptypeattribute a
                                             INNER JOIN assistattribute b
                                               ON a.attributeid = b.attributeid
                                      WHERE  typeid = @Assist2TypeID) ls2
                             ON @attrib2 <> -1
                                AND ls2.ptypeid = p1.typeid
                           LEFT JOIN (SELECT a.ptypeid,
                                             a.attributeid,
                                             b.typeid
                                      FROM   ptypeattribute a
                                             INNER JOIN assistattribute b
                                               ON a.attributeid = b.attributeid
                                      WHERE  typeid = @Assist3TypeID) ls3
                             ON @attrib3 <> -1
                                AND ls3.ptypeid = p1.typeid
                           LEFT JOIN (SELECT a.ptypeid,
                                             a.attributeid,
                                             b.typeid
                                      FROM   ptypeattribute a
                                             INNER JOIN assistattribute b
                                               ON a.attributeid = b.attributeid
                                      WHERE  typeid = @Assist4TypeID) ls4
                             ON @attrib4 <> -1
                                AND ls4.ptypeid = p1.typeid
                    WHERE  p1.[typeid] <> '00000'
                           AND stop = CASE @ifstop
                                        WHEN '0' THEN '0'
                                        ELSE stop
                                      END
                           AND (parid LIKE @szPtypeId + '%'
                                 OR p1.typeid = @szPtypeid)
                           AND isnull(ls1.attributeid, -1) = CASE
                                                               WHEN @attrib1 = -1 THEN isnull(ls1.attributeid, -1)
                                                               ELSE @attrib1
                                                             END
                           AND isnull(ls2.attributeid, -1) = CASE
                                                               WHEN @attrib2 = -1 THEN isnull(ls2.attributeid, -1)
                                                               ELSE @attrib2
                                                             END
                           AND isnull(ls3.attributeid, -1) = CASE
                                                               WHEN @attrib3 = -1 THEN isnull(ls3.attributeid, -1)
                                                               ELSE @attrib3
                                                             END
                           AND isnull(ls4.attributeid, -1) = CASE
                                                               WHEN @attrib4 = -1 THEN isnull(ls4.attributeid, -1)
                                                               ELSE @attrib4
                                                             END) p1
                   LEFT JOIN Ptypecolor b
                     ON p1.typeid = b.ptypeid
                   LEFT JOIN Ptypesize c
                     ON p1.typeid = c.Ptypeid) p,
           (SELECT ptypeid,
                   sum(isnull(-qty, 0))         AS qty,
                   sum(isnull(-S_Tax_total, 0)) AS S_Tax_total,
                   sum(isnull(tqty, 0))         AS tqty,
                   sum(isnull(T_Tax_total, 0))  AS T_Tax_total,
                   sum(isnull(-salemoney, 0))   AS salemoney,
                   sum(isnull(-taxtotal, 0))    AS taxtotal,
                   sum(isnull(-Tax_total, 0))   AS Tax_total,
                   colorid,
                   sizeid
            FROM   (SELECT Ptypeid,
                           sum(isnull([qty], 0))       AS [Qty],
                           sum(isnull([Tax_total], 0)) AS S_Tax_total,
                           0                           AS [TQty],
                           0                           AS T_Tax_total,
                           sum(isnull([salemoney], 0)) AS SaleMoney,
                           sum(isnull([taxtotal], 0))  AS Taxtotal,
                           sum(isnull([tax_total], 0)) AS Tax_total,
                           colorid,
                           sizeid
                    FROM   #tmp_data
                    WHERE  qty < 0
                    GROUP  BY ptypeid,
                              vchtype,
                              colorid,
                              sizeid
                    UNION ALL
                    SELECT Ptypeid,
                           0                           AS [Qty],
                           0                           AS S_Tax_total,
                           sum(isnull([qty], 0))       AS [TQty],
                           sum(isnull([Tax_total], 0)) AS T_Tax_total,
                           sum(isnull([salemoney], 0)) AS SaleMoney,
                           sum(isnull([taxtotal], 0))  AS Taxtotal,
                           sum(isnull([tax_total], 0)) AS Tax_total,
                           colorid,
                           sizeid
                    FROM   #tmp_data
                    WHERE  qty > 0
                    GROUP  BY ptypeid,
                              vchtype,
                              colorid,
                              sizeid) C
            GROUP  BY ptypeid,
                      colorid,
                      sizeid) Salebill
    WHERE  p.[typeid] = Salebill.ptypeid
           AND p.sizeid = salebill.sizeid
           AND p.colorid = salebill.colorid

    SELECT p.[typeid]                                                     AS ptypeid,
           sum(qty)                                                       AS qty,
           sum(S_Tax_total)                                               AS S_Tax_total,
           sum(Tqty)                                                      AS Tqty,
           sum(T_Tax_total)                                               AS T_Tax_total,
           sum(qty) - sum(Tqty)                                           AS Sqty,
           sum(S_Tax_total) - sum(T_Tax_total)                            AS SX_Tax_total,
           sum(Tax_total)                                                 AS tax_total,
           sum(taxtotal)                                                  AS taxtotal,
           sum(SaleMoney) - sum(Tax_total)                                AS DeductTotal,
           
           ROUND(CAST(sum(qty) - sum(Tqty) AS numeric(24,10)) * CAST(RetailPrice AS numeric(24,10)),@dig_total) AS RetailTotal,
           RIGHT('00000' + CAST(colorid AS VARCHAR), 5)                   AS pctypeid,
           RIGHT('00000' + CAST(sizeid AS VARCHAR), 5)                    AS pstypeid
    FROM   #table_P p
    GROUP  BY p.[typeid],
              p.sizeid,
              p.colorid,
              retailprice
    HAVING abs(sum(qty)) + abs(sum(Tqty)) <> 0
    ORDER  BY p.[typeid],
              p.colorid,
              p.sizeid

GO

IF object_id('tempdb..#table_P') IS NOT NULL
  DROP TABLE #table_P

IF object_id('tempdb..#tmp_data') IS NOT NULL
  DROP TABLE #tmp_data

SET QUOTED_IDENTIFIER OFF

GO

SET ANSI_NULLS ON

GO 
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


Create PROCEDURE  FZQueryRetailSaleList_BS  
(     
      @szPtypeId  	varchar(50),  
      @szKtypeid        varchar(2000),  
      @szBtypeid        varchar(50),  
      @szBeginData 	varchar(50),  
      @szEndData 	varchar(50),  
      @ifstop           varchar(2),  
      @attrib1  	int =-1,  
      @attrib2  	int =-1,  
      @attrib3          int =-1,  
      @attrib4          int =-1 ,  
      @Assist1TypeID    int =-1,  
      @Assist2TypeID    int =-1,  
      @Assist3TypeID    int =-1,  
      @Assist4TypeID    int =-1,  
      @SaleTraitName    varchar(1000),  
      @branchid         varchar(2000),
      @OperatorId       varchar(50)='',
      @ifxiaopiao       VARCHAR(2),     --是否包含未过账小票（1：是，0：否）
      @ifdraft          VARCHAR(2)      --是否包含零售单草稿（1：是，0：否）
 )  
 AS  

--设置变量用于操作员拥有所有多级权限时，优化查询
DECLARE @PowerRangeP BIT --商品
DECLARE @PowerRangeE BIT --职员
DECLARE @PowerRangeA BIT --科目
DECLARE @PowerRangeB BIT --客户
DECLARE @PowerRangeC BIT --机构
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 0 AND TypeID = '00000') SET @PowerRangeP = 1 ELSE SET @PowerRangeP = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 1 AND TypeID = '00000') SET @PowerRangeE = 1 ELSE SET @PowerRangeE = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 3 AND TypeID = '00000') SET @PowerRangeA = 1 ELSE SET @PowerRangeA = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 4 AND TypeID = '00000') SET @PowerRangeB = 1 ELSE SET @PowerRangeB = 0
IF EXISTS (SELECT 1 FROM UserPowerRange WHERE EtypeID = @OperatorId AND BaseType = 5 AND TypeID = '00000') SET @PowerRangeC = 1 ELSE SET @PowerRangeC = 0



IF OBJECT_ID('tempdb..#FilterB','U') IS NOT NULL   
DROP TABLE #FilterB  
IF OBJECT_ID('tempdb..#FilterE','U') IS NOT NULL   
DROP TABLE #FilterE  
--IF OBJECT_ID('tempdb..#FilterP','U') IS NOT NULL   
--DROP TABLE #FilterP  
IF OBJECT_ID('tempdb..#FilterK','U') IS NOT NULL   
DROP TABLE #FilterK  
CREATE TABLE #FilterB (TypeId VARCHAR(50))    
CREATE TABLE #FilterE (TypeId VARCHAR(50))    
--CREATE TABLE #FilterP (TypeId VARCHAR(50),PORDER INT)    
CREATE TABLE #FilterK (KtypeId VARCHAR(50))      
INSERT  #FilterB(TypeId) SELECT  TypeId FROM  FN_GetPowerRangeBList(@OperatorId, @szBtypeid, '2,3,4,6')     
INSERT  #FilterE(TypeId) SELECT  TypeId FROM  FN_GetPowerRangeEList(@OperatorId, '') 
INSERT  #FilterK(KtypeId) SELECT  KtypeId FROM  FN_GetStockListOfBranch(@OperatorID, @BranchId, @szKtypeid) 


if object_id('tempdb..#table_S') is not null drop table #table_S  
if object_id('tempdb..#table_P') is not null drop table #table_P  

Declare @tempPtypeID Varchar(50)
SET @tempPtypeID=@szPtypeId

if @branchid is null 
   set  @branchid=''   

if @szPtypeId is null or  @szPtypeId=''
   set  @szPtypeId='%'  

IF OBJECT_ID('tempdb..#temp_data') IS NOT NULL 
   DROP TABLE #temp_data 
CREATE TABLE #temp_data   --创建临时表
(
ptypeid VARCHAR(50),
Qty  numeric(24,10),
S_Tax_total  numeric(24,10),
TQty  numeric(24,10),
T_Tax_total  numeric(24,10),
Taxtotal  numeric(24,10),
SaleMoney  numeric(24,10),
tax_total  numeric(24,10),
vchtype int

)

DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 
--select @dig_qty  ,@dig_price ,@dig_total  ,@dig_dis  ,@dig_tax  ,@dig_rate 

if @SaleTraitName='全部' 
   set @SaleTraitName=''   


	INSERT INTO #temp_data 
	SELECT   s.ptypeid,    --统计过账零售单
				  ds.[qty]      	AS Qty, 	
				  ds.[tax_total]  	AS S_Tax_total,  
				  ds.[qty]		AS TQty,   		
				  ds.[tax_total]	AS T_Tax_total, 	
				  ds.[taxtotal] 	AS Taxtotal,			
				  ds.[salemoney]   	AS SaleMoney,
				  ds.[tax_total]   	AS tax_total,
				  s.Vchtype  	
	from Dlydata s,dlydatadetail ds 
	where S.[date] between @szBeginData and @szEndData 
	and  s.vchtype in(12,100) 
	and s.redold='F'
	AND s.dlyorder = ds.dlyorder
	and ((1=@PowerRangeB AND s.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where s.BtypeId = FilterB.TypeId))  
    and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where s.EtypeId = FilterE.TypeId))  
    and exists(select 1  from #FilterK FilterK where s.ktypeId = Filterk.KtypeId)
	and (CustValue1 like '%'+@SaleTraitName+'%'  
			or CustValue2 like '%'+@SaleTraitName+'%'  
			or CustValue3 like '%'+@SaleTraitName+'%'  
			or CustValue4 like '%'+@SaleTraitName+'%'  
			or CustValue5 like '%'+@SaleTraitName+'%'  
			or CustValue6 like '%'+@SaleTraitName+'%'  )	


IF  @ifdraft=1  --统计包含零售单草稿
BEGIN 
INSERT INTO #temp_data
            Select	b.Ptypeid,
			-bd.[qty]      		AS Qty, 	
			-bd.[tax_total]  	As S_Tax_total,  
			-bd.[qty]		    AS TQty,   		
			-bd.[tax_total]		AS T_Tax_total, 	
			-bd.[taxtotal] 		AS Taxtotal,			
			-bd.[salemoney]   	AS SaleMoney,
			-bd.[tax_total]   	AS tax_total,
            b.vchtype
    FROM    Bakdly b, BakDlyDetail bd
    WHERE   b.[date] BETWEEN @szBeginData AND @szEndData
	    AND b.vchtype IN ( 12, 100)
	    AND b.Ptypeid<>''
        AND b.dlyorder = bd.dlyorder           
        and ((1=@PowerRangeB AND b.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where b.BtypeId = FilterB.TypeId))  
        and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where b.EtypeId = FilterE.TypeId))  
        and exists(select 1  from #FilterK FilterK where b.ktypeId = Filterk.KtypeId)
        AND ( CustValue1 LIKE '%' + @SaleTraitName + '%'
              OR CustValue2 LIKE '%' + @SaleTraitName + '%'
              OR CustValue3 LIKE '%' + @SaleTraitName + '%'
              OR CustValue4 LIKE '%' + @SaleTraitName + '%'
              OR CustValue5 LIKE '%' + @SaleTraitName + '%'
              OR CustValue6 LIKE '%' + @SaleTraitName + '%'
            )
      AND EXISTS(SELECT 1 FROM dbo.DlyNdx x WHERE x.Vchcode = b.Vchcode AND x.Draft IN (1,4,10))
END

IF  @ifxiaopiao=1 AND @SaleTraitName = '' --统计包含未过账小票
BEGIN

INSERT INTO #temp_data
            Select	
             PSL.Ptypeid,
			-SUM(PSL.[qty])  AS Qty, 	
			-SUM(PSL.[total])  As S_Tax_total,  
			-SUM(PSL.[qty])	AS TQty,   		
			-SUM(PSL.[total])	AS T_Tax_total, 	
			        0   AS  Taxtotal,			
			-SUM(PSL.[total])  AS SaleMoney,
			-SUM(PSL.[total])  AS tax_total,
            vchtype=12 --POS过账后默认为零售单
           
    FROM    dbo.tpx_SaleList PSL,dbo.tpx_SaleIndex PSI
    WHERE   PSI.[Saledate] BETWEEN @szBeginData AND @szEndData
	        AND PSL.Ptypeid<>''
            AND PSL.ZBKeyId=PSI.keyId 
            and ((1=@PowerRangeB AND PSI.BtypeId LIKE @szBtypeid + '%') OR exists(select 1  from #FilterB FilterB  where PSI.BtypeId = FilterB.TypeId))  
            and ((1=@PowerRangeE) OR exists(select 1  from #FilterE FilterE  where PSI.Salesman = FilterE.TypeId))  
            and exists(select 1  from #FilterK FilterK where PSI.ktypeId = Filterk.KtypeId)
            AND PSI.Draft=0 --Draft 结存标志[0-POS小票,1-草稿] 
            GROUP BY PSL.Ptypeid
            
            /*
            AND ( CustValue1 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue2 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue3 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue4 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue5 LIKE '%' + @SaleTraitName + '%'
                  OR CustValue6 LIKE '%' + @SaleTraitName + '%'
             ) */--POS小票那无自定义类型
END

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

	Select  p1.[typeid],RetailPrice,porder    
		  INTO #tmp_ptype
          From FN_GetPowerRangePList(@OperatorId,@tempPtypeID) p1
  	      left join ( select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b   
   			 where a.attributeid = b.attributeid and typeid = @Assist1TypeID ) ls1  on  @attrib1 <> -1 and ls1.ptypeid = p1.typeid  
		  left join ( select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b   
             where a.attributeid = b.attributeid and typeid = @Assist2TypeID ) ls2  on  @attrib2 <> -1 and ls2.ptypeid = p1.typeid  
          left join ( select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b  
             where a.attributeid = b.attributeid and typeid = @Assist3TypeID ) ls3  on  @attrib3 <> -1 and ls3.ptypeid = p1.typeid  
		  left join ( select a.ptypeid,a.attributeid,b.typeid from ptypeattribute a,assistattribute b  
			 where a.attributeid = b.attributeid and typeid = @Assist4TypeID ) ls4  on  @attrib4 <> -1 and ls4.ptypeid = p1.typeid  
     Where stop =case @ifstop when '0' then '0' else stop end and p1.typeid<>'00000'  
	 and (parid like @szPtypeId+'%' or p1.typeid =@szPtypeid )    
	 and isnull(ls1.attributeid,-1) =  case when @attrib1 = -1 then isnull(ls1.attributeid,-1) else @attrib1 end  
     and isnull(ls2.attributeid,-1) =  case when @attrib2 = -1 then isnull(ls2.attributeid,-1) else @attrib2 end  
     and isnull(ls3.attributeid,-1) =  case when @attrib3 = -1 then isnull(ls3.attributeid,-1) else @attrib3 end  
     and isnull(ls4.attributeid,-1) =  case when @attrib4 = -1 then isnull(ls4.attributeid,-1) else @attrib4 end  


------------------------------------------------------------------
select	p.[typeid]							as ptypeid,
		porder,  
        sum(qty) 							as qty,
		sum(Tqty)							as Tqty,
        sum(qty) -sum(Tqty)					as Sqty,  
        sum(S_Tax_total)					as S_Tax_total,  
		sum(T_Tax_total)					as T_Tax_total,
		sum(S_Tax_total)-sum(T_Tax_total)	as SX_Tax_total, 	
		sum(taxtotal)						as taxtotal, 
		ROUND(CAST((SUM(qty) - SUM(Tqty)) AS NUMERIC(24,10))*CAST(RetailPrice AS NUMERIC(24,10)),@dig_total) RetailTotal,
		sum(SaleMoney)						as SaleMoney,
		sum(tax_total)						as tax_total,
        sum(SaleMoney)-sum(tax_total)		as DeductTotal
From
(  	Select   p.[typeid],   
	         isnull([Qty],0)		AS [Qty],
			 isnull(S_Tax_total,0)	as [S_Tax_total],
			 isnull(Tqty,0)			AS Tqty,
			 isnull(T_Tax_total,0)  as [T_Tax_total],	
			 isnull([SaleMoney], 0) AS [SaleMoney],		 
	         isnull([taxtotal], 0)  as Taxtotal,
	         isnull([tax_total], 0) as Tax_total,  	    
	         p.porder,
	         p.RetailPrice  	
	  From 
		      #tmp_ptype p 
		  LEFT join 
			(		SELECT	ptypeid,
       						sum(isnull(-qty,0)) 	        AS qty,
       						sum(isnull(-S_Tax_total,0))     AS S_Tax_total,
       						sum(isnull(tqty,0))				AS tqty,  		
       						sum(isnull(T_Tax_total,0))      AS T_Tax_total,
       						sum(isnull(-taxtotal,0))        AS taxtotal,		
       						sum(isnull(-salemoney,0))       AS SaleMoney,
       						sum(isnull(-tax_total,0))       AS tax_total		
	   				from
					(  	
						Select		  ptypeid,
									  sum(isnull([qty], 0))          	AS Qty, 		--销售数量
									  sum(isnull([tax_total],0))     	As S_Tax_total,  	--价税合计（销售）
									  0          						AS TQty,   		--退货数量
									  0          					  	AS T_Tax_total, 	--价税合计（退货）
									  sum(isnull([taxtotal],0))      	AS Taxtotal,		--税额			
									  sum(isnull([salemoney],0))     	AS SaleMoney,
									  sum(isnull([tax_total],0))     	AS tax_total  	
						FROM #temp_data
						WHERE Qty < 0
						GROUP BY  ptypeid,vchtype  		
						UNION ALL
						Select		  Ptypeid,  
									  0									AS Qty, 		--销售数量
									  0									AS S_Tax_total,  	--价税合计（销售）
									  sum(isnull([qty], 0))			    AS TQty,   		--退货数量
									  sum(isnull([tax_total],0))		AS T_Tax_total, 	--价税合计（退货）
									  sum(isnull([taxtotal],0))      	AS Taxtotal,		--税额				  
									  sum(isnull([salemoney],0))     	AS SaleMoney,
									  sum(isnull([tax_total],0))     	AS tax_total			
						FROM #temp_data
						WHERE Qty > 0          		      	     		      			      
    					GROUP BY  ptypeid,vchtype  
					) C  
	   			group by ptypeid    
         ) Salebill  on p.[typeid]=Salebill.ptypeid  
)p  
group by [typeid],p.porder,RetailPrice  
order by p.porder,p.[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].[FZZ_CreateRed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FZZ_CreateRed]
GO
--  **********************************************************************************************
--  ||                                                                                        
--  ||   过程名称：FZZ_CreateRed                               
--  ||   过程功能：--红字反冲  modify by 老罗 2012-08-15
--  ||=========================================================================================
--  ||   参数说明：  参数名称         类型                意义                     输入输出
--  ||            -----------------------------------------------------------------------------
--  ||          @nVchcode         numeric(10, 0),        需要红冲的单据系统编号
--  ||         	@szptypeido       varchar(50) output,      商品编号
--  ||         	@szbtypeido       varchar(50) output,      往来单位
--  ||         	@szatypeido       varchar(50) output,      会计科目
--  ||         	@szktypeido       varchar(50) output       仓库编号
--  ||=========================================================================================   
--  ||   返回值：         值                                     说明
--  ||       ----------------------------------------------------------------------------------
--  ||         0          			  执行成功
--  ||         -9         			  数据库操作失败   
--  ||         -1        			  库存数量不够     
--  ||         -14      			  过帐日期小于本月的起始日期
--  ||         -16                                已经红冲(红字单据)
--  ||         -17                                已经红冲(原始单据)
--  ||         －2		      		  Failure
--  ||         －3		      		  数量为零
--  ||         －4                                数据库操作失败
--  ||         －5                                没有成本
--  ||         －18                               单据未过账不能红冲
--  ||         －100		   		  出现了负库存
--  ||         －44		   		  更新库存失败
--  ||	       －42	                  	  更新应收失败
--  ||         －41		     		  更新应付失败
--  ||         －10		     		  单据已经上（下）传不能红冲
--  ||        		 -201                             委托、受托库存数量不够
--  ||      	         -203                             数量为零  对于委托、受托调价数量可以为0
--  ||                   -205                             委托、受托出库金额为零
--  ||                   -204			          写商品颜色、尺码明细失败
--  ||      	         -299                             商品或商品分类已经删除
--  ||                   -300			 商场零售单已经结算不能红冲
--  ||==========================================================================================
--*********************************************************************
--modify by 老罗 2012-08-23 重新处理dlyndxb表，修改原始单据的红冲人
--**********************************************************************
CREATE PROCEDURE FZZ_CreateRed
(	
	@nVchcode numeric(10, 0),
	@szptypeido varchar(50) output,
	@szbtypeido varchar(50) output,
	@szatypeido varchar(50) output,
	@szktypeido varchar(50) output,
	@szGeneralTotal  numeric(24,10)=0 output, --返回金额目前为vip 的新增积分	
    @RetTotalSaleMoney numeric(24,10)=0 output, --返回VIP的减少金额
    @RetTotalJFJE      numeric(24,10)=0 output, --返回VIP的减少积分金额
    @RetVipCardId  int=0 output,
	@vipcardno  varchar(50)=0 output,
	@newvchcode int=0 output,
	@CurrentOperator varchar(50)='',
    @message varchar(200) output,
    @CallSelf BIT = 0
)
AS
	set nocount on

    declare @TRANSFLAG varchar(20) 
    declare @errorOrder int
    set @TRANSFLAG=@szbtypeido
	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  @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), @TAX_ID  varchar(50),
		 @SALE_INCOME_ID       varchar(50), @SALE_COST_ID    varchar(50), @OTHER_INCOME_ID varchar(50), @aorderdlycode int,
		 @PRICEALLOT_CHANGE_ID varchar(50), @ALLOT_INCOME_ID varchar(50), @BUY_BUYBACK_ID  varchar(50),
		 @GOODS_GIVE_ID        varchar(50), @GOODS_GIVEME_ID varchar(50), @GOODS_PRODUCE_ID varchar(50),
		 @LENDOUT_STOCK        varchar(50), @BORROWIN_STOCK  varchar(50), @aordercode      int        
	
	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 @TAX_ID = '0000200004'
	set @SALE_INCOME_ID='0000300001'
	set @SALE_COST_ID='0000400001'
	set @OTHER_INCOME_ID ='0000300003'
	set @PRICEALLOT_CHANGE_ID='000030000200005'
	set @ALLOT_INCOME_ID = '000030000200003'
	set @BUY_BUYBACK_ID = '000030000200004'
	set @GOODS_GIVE_ID = '000040000200002'
	set @GOODS_GIVEME_ID = '000030000200002'
	set @GOODS_PRODUCE_ID = '000030000200006'
	set @LENDOUT_STOCK ='9999999999'
	set @BORROWIN_STOCK ='9999999998'
	declare @SEND_GOODS_STOCK_ID varchar(50),
		@COMMISSION_STOCK_ID varchar(50),
		@RECOMMISSION_STOCK_ID varchar(50)
	set @SEND_GOODS_STOCK_ID='9999900001'
	set @COMMISSION_STOCK_ID='9999900002'
	set @RECOMMISSION_STOCK_ID='9999900003'

	declare @tDate        varchar(10),   @nCostMode       int
	declare @nVchType     numeric(4,0),  @szAtypeId       varchar(50),   @szPtypeId      varchar(50),   @szbTypeId varchar(50),
		@szEtypeId    varchar(50),   @szKtypeId       varchar(50),   @szKtypeId2     varchar(50),   @convert   numeric(24,10)
	declare @dTotal       numeric(24,10),@dQty            numeric(24,10),@nPeriod        int,           @szBlockno varchar(20),
		@szProdate    varchar(12),   @dPrice          numeric(24,10),@bargainTotal   numeric(24,10),@colorid   int
		
	declare @ddiscount    numeric(24,10),@ddiscountprice  numeric(24,10),@ddiscounttotal numeric(24,10)
	declare @dtax         numeric(24,10),@dtaxprice       numeric(24,10),@dtaxtotal      numeric(24,10),@dtax_total numeric(24,10)
	declare @dcostprice   numeric(24,10),@dcosttotal      numeric(24,10),@szmemo         varchar(60),   @period     char(2)
	declare @usedtype     char(1)       ,@nGoodsNo        int,           @nRet           smallint,@nRetJ           smallint
	declare @execsql      varchar(5000), @cRed            char(1),	     @inputno        varchar(50)
	declare @szTemp       varchar(50),   @dTemp           numeric(24,10),@dTemp1         numeric(24,10)
	declare @nNewVchcode  numeric(10,0), @ifcheck        char(1)  ,     @CustValue1     varchar(50),
		@CustValue2     varchar(50)  ,@CustValue3     varchar(50)  ,@CustValue4     varchar(50),  
		@CustValue5     varchar(50)  ,@CustValue6     varchar(50)        
	declare @checke       varchar(50),   @Number          varchar(256),  @Summary        varchar(256),  @Comment    varchar(256)
	declare @type         int,           @InvoiceTotal    numeric(24,10),@InvoiceTag     int,           @PDetail    int,
		@Dtypeid       varchar(50),   @oDlyOrder       int,           @nDlyOrder      int,           @cDlyOrder  int,
	        @ifSupply bit ,@ifout bit,   @YSYFTotal       numeric(24,10),@LJYSYFTotal    numeric(24,10),
		@packcode    varchar(100),   @packRate       numeric(24,10), @packQty        numeric(24,10),@cRedold  char(1),
		@vchtypeList VARCHAR(1000)
	declare @unitRate  numeric(24,10),@singleunit int,@branchid3 varchar(50),@btypeid2 varchar(50)
--------------------------------------- 生成换货记录用到的变量---------------------------------------------------------Begin
	Declare @nowChange    numeric(24,10),@oldchang    numeric(24,10),@ifjs 		  int,
		@BarterRate  numeric(24,10),@BarterTerm  numeric(24,10),@nowChangeTem      numeric(24,10),
   		@ifModify    bit,	    @discount    numeric(24,10),@AddChang         numeric(24,10),
		@CutChang    numeric(24,10),@LowLimitation   numeric(24,10),@MarketDiscount   numeric(24,10),
   		@total       numeric(24,10),@iniChange    numeric(24,10),@BackMoney        numeric(24,10),
		@MarketDiscount1   numeric(24,10),@RetailBackFlag BIT,@PHID    INT

    DECLARE @OPID int --业务信息ID
	SET @OPID = 0
	SET @PHID = 0 --业务类型ID

	SET @CutChang=0
	SET @AddChang=0
	---------------------------------------------------------------------------------------------------------------------------------------------End
	declare @JoinCostPrice numeric(24,10),@JoinCostTotal numeric(24,10),@dqty_j numeric(24,10)--加盟店配货红冲专用
	declare @LimitTime	  varchar(10),	
		@InputNo1         varchar(50),--自营店配货单发货人
		@InputNo2         varchar(50),--自营店配货单验收人	
		@InputNo3         varchar(50),--自营店配货单拒收人
		@inputno4         varchar(50),
		@inputno5         varchar(50),   @unit int,
 		@zddiscount   numeric(24,10),    @zddiscountprice  numeric(24,10),@VIPCardID        int ,
 		@AtypeId      varchar(50) ,      @AtypeTotal       numeric(24,10),@VIPDisCount      NUMERIC(24,10) ,
 		@preferential numeric(24,10),    @BarterType       int ,  	  @SaleMoney        numeric(24,10),
        @TotalSaleMoney   numeric(24,10),@TotalJFJE        numeric(24,10),@flag             int,
        @Branchid         varchar(50),   @Branchid2        varchar(50),   @Salemode         varchar(30),
        @draft            int,		 @CurrUndoIntegral int,	          @LastUndoIntegral int,
		@siteid   INT, @ForeVipBalance NUMERIC(24,10),@billtype TINYINT,@qtyTemp NUMERIC(24,10),@retailprice numeric(24,10)
    set @inputno4=''		
    set @TotalSaleMoney=0
    set @TotalJFJE=0
    set @nRetJ=0
    set @vchtypeList=''
	set @nowChange = 0
	SELECT TOP 1 @szTemp=subvalue from sysdata where subname='startdate'	
	exec FZGetsysvalue 'period',@period		
	if not exists(Select 1 from dlyndx where vchcode=@nVchcode) Return -2
    SELECT TOP 1 @nVchType = VchType ,
            @tDate = ISNULL(Date, '') ,
            @szbTypeId = ISNULL(btypeid, '') ,
            @szEtypeId = ISNULL(etypeid, '') ,
            @szKtypeId = ISNULL(ktypeid, '') ,
            @szKtypeid2 = ISNULL(ktypeid2, '') ,
            @Number = ISNULL(number, '') ,
            @Summary = ISNULL(summary, '') ,
            @Comment = ISNULL(Comment, '') ,
            @period = ISNULL(period, '1') ,
            @ifcheck = ISNULL(ifcheck, 0) ,
            @checke = ISNULL(checke, '') ,
            @dTotal = ISNULL(total, 0) ,
            @Dtypeid = ISNULL(Dtypeid, '') ,
            @inputno = ISNULL(inputno, '') ,
            @BarterType = ISNULL(BarterType, 0) ,
            @VIPDisCount = ISNULL(VIPDisCount, 0) ,
            @cRed = ISNULL(Redword, 'F') ,
            @LimitTime = ISNULL(limitTime, '') ,
            @InputNO1 = ISNULL(INputNo1, '') ,
            @InputNO2 = ISNULL(INputNo2, '') ,
            @InputNO3 = ISNULL(INputNo3, '') ,
            @VIPCardID = ISNULL(VIPCardID, 0) ,
            @zddiscountprice = ISNULL(zddiscountprice, 0) ,
            @zddiscount = ISNULL(zddiscount, 0) ,
            @AtypeId = ISNULL(atypeid, '') ,
            @preferential = ISNULL(preferential, 0) ,
            @atypetotal = ISNULL(atypeTotal, 0) ,
            @BackMoney = ISNULL(BackMoney, 0) ,
            @flag = flag ,
            @Branchid = branchid ,
            @ifout = ifout ,
            @draft = draft ,
            @RetailBackFlag = RetailBackFlag ,
            @CurrUndoIntegral = ISNULL(CurrUndoIntegral, 0) ,
            @LastUndoIntegral = ISNULL(LastUndoIntegral, 0) ,
            @YSYFTotal = ISNULL(YSYFTotal, 0) ,
            @LJYSYFTotal = ISNULL(LJYSYFTotal, 0) ,
            @siteid = siteid ,
            @cRedold = Redold ,
            @inputno4 = inputno4 ,
            @inputno5 = inputno5 ,
            @ForeVipBalance = ISNULL(ForeVipBalance, 0) ,
            @vchtypeList = ISNULL(Orderlist, '') ,
            @billtype = billtype ,
            @qtyTemp = qty ,
            @branchid2 = branchid2 ,
            @PHID = PHID ,
            @btypeid2 = btypeid2 ,
            @branchid3 = branchid3
    FROM    dlyndx
    WHERE   Vchcode = @nVchcode
	
	--红冲专用
    DECLARE @Redbranchid VARCHAR(50) ,
        @RedOtherVchCode NUMERIC(10, 0)
    SET @Redbranchid = @branchid
 --验收机构

    IF @nVchType IN ( 222, 232, 234, 224 ) 
        SELECT TOP 1
                @RedOtherVchCode = dlyvchcode
        FROM    Dlyndx
        WHERE   vchcode = @nVchcode 


    SELECT TOP 1
            @vipcardno = cardno
    FROM    vipcards
    WHERE   cardid = @VIPCardID
	
    IF @nVchType = 250 
    BEGIN
        --exec @nRet=F_RED_MarketRed @nVchcode
        RETURN 0
    END
    IF @nvchtype IN ( 212, 218, 215 ) 
    BEGIN
        EXEC @nRet= FZZ_CreateRed_ph @nVchcode, @szptypeido OUTPUT,
            @szbtypeido OUTPUT, @szatypeido OUTPUT, @szktypeido OUTPUT,@CurrentOperator
        IF @nRet >= 0 
        BEGIN
            RETURN 0
        End
        ELSE 
            RETURN @nRet	
    END

	if @nvchtype in (211,214,230) return -@nvchtype

	if @draft<>2 return -18
	if @szTemp>@tDate return -14
	if @nvchtype = 24 SET  @type=4
	else
	if @nvchtype in (25,26,30,50) SET @type=1
	else
	if @nvchtype in (27,28,31,51) set @type=5
	--print 'cdcdcdced'
	if @cRed='T'  return -16		
	if @cRedold='T' return -17		
	--begin tran RedAccount
		--加盟配货，加盟退货红冲时，删除未验收的草稿	

    DECLARE @ProcType VARCHAR(50)  
    SELECT TOP 1 @ProcType = subvalue
    FROM    sysdata
    WHERE   subName = 'ProcTypeName'   
  
    IF  @CallSelf = 0 
    	BEGIN TRAN RedAccount  
		
		if @nVchType in(222,234)
		BEGIN
			--DELETE FROM DlyNdx where VchCode in (select dlyvchcode from Dlyndx where 
			--  checkandaccept=0 AND vchcode =@nVchcode and dlyvchcode <>0)
			--删除后，还要重算虚拟库存
			DECLARE @dlyvchcode int
			SELECT TOP 1 @dlyvchcode=dlyvchcode from Dlyndx where checkandaccept=0 AND vchcode =@nVchcode and dlyvchcode <>0
			IF @dlyvchcode<>0 AND NOT @dlyvchcode IS null
				EXEC FZDeleteDlyndx @dlyvchcode
		END

		set @Summary='红字反冲：'+@Summary
		--if @nvchtype in(170,230) set @inputno4=@CurrentOperator
		--exec @nNewVchcode = F_D_insertDlyNdx  @tDate,@Number, @nVchType,@Summary,@Comment, @szBtypeid,
		--@szEtypeid,@szKtypeid,@szKtypeid2,@ifcheck,@checke,@Period,@accounte,@inputno,'2','T',@Dtypeid
        INSERT  INTO [dbo].[DlyNdx]
                ( [Date] ,            [number] ,                 [VchType] ,                  [summary] ,
                  [Comment] ,         [btypeid] ,                [etypeid] ,                  [ktypeid] ,
                  [ktypeid2] ,        [ifcheck] ,                [checke] ,                   [period] ,
                  [inputno] ,         [draft] ,                  [redword] ,                  VIPCardID ,
                  VIPDisCount ,       BarterType ,               Dtypeid ,                    LimitTime ,
                  InputNo1 ,          InputNo2 ,                 InputNo3 ,                  zddiscount ,
                  zddiscountprice ,   atypeid ,                  preferential ,              atypeTotal ,
                  backMoney ,         flag ,                     branchid ,                  accountTime ,
                  RetailBackFlag ,    CurrUndoIntegral ,         LastUndoIntegral ,          foreignvchcode ,
                  siteid ,            inputno4 ,                 inputno5 ,                  ForeVipBalance ,
                  Orderlist ,         BillType ,                 Total ,                     qty ,
                  branchid2 ,         PHID ,                     btypeid2 ,                  branchid3
                )
        VALUES  ( @TDate ,             @number ,                 @nVchType ,                  @summary ,
                  @Comment ,           @szbtypeid ,              @szetypeid ,                @szktypeid ,
                  @szktypeid2 ,        @ifcheck ,                @checke ,                   @Period ,
                  @inputno ,           2 ,                       'T' ,                       @VIPCardID ,
                  @VIPDisCount ,       @BarterType ,             @Dtypeid ,                  @LimitTime ,
                  @InputNo1 ,          @InputNo2 ,               @InputNo3 ,                 @zddiscount ,
                  @zddiscountprice ,   @AtypeId ,                @preferential ,             @atypetotal ,
                  @backmoney ,         @flag ,                   @Branchid ,                  GETDATE() ,
                  @RetailBackFlag ,    @CurrUndoIntegral ,       @LastUndoIntegral ,         @newvchcode ,
                  @siteid ,            @inputno4 ,               @inputno5 ,                 @ForeVipBalance ,
                  @vchtypeList ,       @Billtype ,               @dTotal ,                   @qtyTemp ,
                  @branchid2 ,         @PHID ,                   @btypeid2 ,                 @branchid3
                )
		if @@rowcount=0 or @@Error <> 0
		begin
			set @nRet = -9
			goto error
		end
		else 
		Begin
			set @nNewVchcode=@@identity
			set @newvchcode=@nNewVchcode
		end
		update dlyndx set redold='T',dlyvchcode=@nNewVchcode where vchcode=@nVchcode
		update dlydata set redold='T' where vchcode=@nVchcode
        UPDATE  dlyndx
        SET     redold = 'T' ,
                YSYFTotal = @YSYFTotal ,
                LJYSYFTotal = @LJYSYFTotal ,
                dlyvchcode = @nVchcode ,
                inputno = @CurrentOperator
        WHERE   vchcode = @nNewVchcode

	declare @phrows int		
	declare @vipcardidT int	
	if @nVchType in (11,45,89,26,24,12,13,222,224,232,234,226,227,100,101)
	begin
		--删除商品唯一码
		--if @nVchType in (11,45,222,232,234,224)
		--	delete from PtypeUniqueCode where vchcode=@nVchcode
		
        SELECT  @execsql = 'declare CreateRed_cursor cursor FORWARD_ONLY STATIC READ_ONLY for '
                + ' select atypeid, ptypeid, ktypeid,qty, price, total, discount, discountprice, discounttotal,'
                + 'tax, taxprice, taxtotal, tax_total, costprice, costtotal,comment, period, usedtype,'
                + 'DlyOrder,InvoiceTotal,InvoiceTag , PDetail ,bargainTotal,colorid,'
				+ '[convert],ifSupply,salemoney,marketDiscount,marketDiscount1,vipdiscount,branchid,Salemode '
                + ',packcode,packRate,packQty,CustValue1,CustValue2, CustValue3, CustValue4, CustValue5, CustValue6,joincostTotal,'
                + 'retailprice,unit,JoinCostPrice,vipcardid,opid,phrows,unitRate,singleunit '
                +' from Dlydata where usedtype=case when vchtype in(24,222,224) then  usedtype else 1 end and Vchcode= '
                + CAST(@nVchcode AS VARCHAR(10))
                + ' order by case when vchtype=24 then qty else dlyorder end'
		
		exec (@execsql)
		OPEN CreateRed_cursor
		fetch next from CreateRed_cursor into @szatypeid, @szPtypeId,@szKtypeid,@dQty,@dPrice,@dTotal,
			@ddiscount,@ddiscountprice, @ddiscounttotal,@dtax,@dtaxprice,@dtaxtotal,@dtax_total,@dcostprice,
			@dcosttotal, @szmemo, @period,@usedtype,@oDlyOrder,@InvoiceTotal,@InvoiceTag ,@PDetail,
			@bargainTotal,@colorid,@convert,@ifSupply,@SaleMoney,@marketDiscount,@marketDiscount1,
			@vipdiscount,@Branchid,@salemode,@packcode,@packRate,@packQty,
			@CustValue1,@CustValue2, @CustValue3, @CustValue4, @CustValue5,
			@CustValue6,@JoinCostTotal,@retailprice,@unit,@JoinCostPrice,@vipcardidT,@OPID,@phrows,@unitRate,@singleunit

		while @@FETCH_STATUS=0
		begin
			set @dQty = -@dQty
			set @dTaxTotal = -@dTaxTotal
			set @dTax_Total = -@dTax_Total
			set @dCostTotal = - @dCostTotal	
			set @dTotal = -@dTotal
			set @dDiscountTotal = -@dDiscountTotal
			set @bargainTotal=-@bargainTotal
			set @Salemoney=-@Salemoney
			set @JoinCostTotal=-@JoinCostTotal
	        set @convert=-1*isnull(@convert,0)

            --红冲时利用这个循环得到积分金额的变化量，以便红冲单据的能够返回积分金额的减少情况 
			if @nVchType in(226,227)
			begin
			    set @TotalSaleMoney=@TotalSaleMoney+@dTax_Total
				if @salemode<>'1' set  @TotalJFJE=@TotalJFJE+@dTax_Total
			end
 			else
			begin
			    set @TotalSaleMoney=@TotalSaleMoney+@Salemoney
				if @salemode<>'1' set  @TotalJFJE=@TotalJFJE+@Salemoney
			end
			--增加红冲草稿
			if @szPtypeId<>'' 
			begin
				SELECT TOP 1 @nCostmode=costmode from ptype where typeid=@szptypeid
			end
			if @dcosttotal=0 and @nCostmode=0 set @ncostmode=4
			set @ncostmode=ISNULL(@ncostmode,0)
			
			insert into bakdly(vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				qty,price,total,costprice,costtotal,discount,discountprice,discounttotal,
				tax,taxprice,taxtotal,tax_total,comment,period,usedtype,
				bargainTotal,colorid,[convert],ifSupply,JoinCostPrice,JoinCostTotal,
				branchid,Salemode,salemoney,packcode,packRate,packQty,costmode,marketDiscount,
				MarketDiscount1,vipdiscount,CustValue1,CustValue2, CustValue3,
				 CustValue4, CustValue5, CustValue6,billType,retailprice,unit,vipcardid,phrows,unitRate,singleunit)
			values(@nNewVchcode,@tDate,@nVchType,@szAtypeID,@szPtypeid,@szBtypeid,@szEtypeid,
				@szKtypeId,@dQty,@dPrice,isnull(@dTotal,0),@dcostPrice,isnull(@dcostTotal,0),
				@ddiscount,@ddiscountprice,@ddiscounttotal,@dtax,@dtaxprice,@dtaxtotal,
				@dtax_total,@szmemo,@period,@usedtype,@bargainTotal,@colorid,@convert,@ifSupply
				,isnull(@JoinCostPrice,0),isnull(@JoinCostTotal,0),@Branchid,@salemode,
				isnull(@SaleMoney,0),@packcode,@packRate,@packQty,@ncostmode,
				isnull(@marketDiscount,0),isnull(@marketDiscount1,0),isnull(@vipdiscount,0),
				@CustValue1,@CustValue2,@CustValue3,@CustValue4,@CustValue5,@CustValue6,
				@Billtype,@retailprice,@unit,@vipcardidT,@phrows,@unitRate,@singleunit)	
			set @cDlyOrder = @@identity 
			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -9
				goto error
			end	
			
			insert into bakdlydetail (DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,
                			BargainTotal,[Convert],DiscountTotal,CostTotal,SaleMoney,JoinCostTotal,phrows,vchcode,usedtype) 
                		select @cDlyOrder,sizeid,colorid,
					case when @nVchType in(12,226,100) then QTY
-- 					     when @nVchType in(222,224) then -1*qty
						else abs(qty) end,
					case when @nVchType in(12,226,100) then Total
-- 					     when @nVchType in(222,224) then -1*Total   
						else abs(Total) end,
					case when @nVchType in(12,226,100) then Taxtotal
-- 					     when @nVchType in(222,224) then -1*Taxtotal    
						else abs(Taxtotal) end,
					case when @nVchType in(12,226,100) then Tax_total
-- 					     when @nVchType in(222,224) then -1*Tax_total    
						else abs(Tax_total) end,
					case when @nVchType in(12,226,100) then BargainTotal 
-- 					     when @nVchType in(222,224) then -1*BargainTotal    
						else abs(BargainTotal) end,
					case when @nVchType in(12,226,100) then [Convert] 
-- 					     when @nVchType in(222,224) then -1*[Convert]    
						else abs([Convert]) end,
					case when @nVchType in(12,226,100) then DiscountTotal
-- 					     when @nVchType in(222,224) then -1*DiscountTotal   
						else abs(DiscountTotal) end,
 					case when @nVchType in(12,226,100) then CostTotal 
-- 					     when @nVchType in(222,224)    then -1*CostTotal 
						else abs(CostTotal) end,
					case when @nVchType in(12,226,100) then SaleMoney
-- 					     when @nVchType in(222,224) then -1*SaleMoney 
						else abs(SaleMoney) end,
					case when @nVchType in(12,226,100) then JoinCostTotal
-- 					     when @nVchType in(222,224) then -1*SaleMoney 
						else abs(JoinCostTotal) end,@phrows,@nNewVchcode,usedtype
                                 from DlydataDetail 
				where DlyOrder = @oDlyOrder
			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -9
				goto error
			end
			              
			if @szPtypeId<>'' 
			begin
				
				SELECT TOP 1  @nCostmode=costmode from ptype where typeid=@szptypeid
				
				if @dcosttotal=0 set @ncostmode=4
				
					Exec @nRet = FZModifyDbf @nVchtype,@nCostmode,@GOODs_ID,@szptypeid,'',@szktypeid,
				@period,@dqty,@dcosttotal,@dTemp output,@cDlyOrder,@branchid
				

				--更改补货标志
				if @nVchType in(11,222,24)
				Begin
					
					if exists(Select [id] From BtypeSupply Where btypeid=@szbtypeid and ptypeid=@szptypeid and colorid=@colorid)
					Begin
					 
					  	if not exists(Select 1 From 
									(select vchcode,btypeid,ptypeid,colorid from dlydata
									        where usedtype =case vchtype when 24 then 2 else usedtype end) s,dlyndx d
									         Where d.vchcode=s.vchcode 
					   		and s.btypeid=@szbtypeid and s.ptypeid=@szptypeid 
					   		and d.draft not in(1,4,8,10,3)and d.redold<>'T' and d.vchtype in(11,222,24)
							and colorid=@colorid )
						Begin
							
							Delete From BtypeSupply where btypeid=@szBtypeid and ptypeid=@szptypeid and colorid=@colorid
						END
						else
						Begin   
						
						   	if not exists(Select 1 From 
									(select vchcode,btypeid,ptypeid,colorid,ifsupply from Dlydata
									where usedtype =case vchtype when 24 then 2 else usedtype end) s,dlyndx d Where d.vchcode=s.vchcode 
					   		and s.btypeid=@szbtypeid and s.ptypeid=@szptypeid 
					   		and d.draft not in(1,4,8,10,3)and d.redold<>'T' and d.vchtype in(11,222,24)
							and colorid=@colorid and s.ifSupply=1)
							Update BtypeSupply
							Set ifSupply =0 Where btypeid=@szBtypeid and ptypeid=@szptypeid and colorid=@colorid
						end
					
					End
				End
				
			end
			else --处理会计科目
			begin		
				
				Exec @nRet = FZModifyDbf @nVchtype,@nCostmode,@szAtypeId,@szptypeid,@szBtypeId,@szktypeid,
				@period,@dqty,@dTotal,@dTemp output,@cDlyOrder,@branchid
			end
		
			if @nRet<0 goto error
			if @nRetJ<0 goto error
			
-- 			Declare @JoinCostTotal_Tem numeric(24,10)
-- 			set @JoinCostTotal_Tem=-@JoinCostTotal
-- 			set @joincostprice=case @dqty when 0 then 0 else dbo.costprice(@JoinCostTotal_Tem/@dQty) end
			set @nCostMode=isnull(@nCostMode,0)
			
			

			insert into Dlydata(vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				qty,price,total,costprice,costtotal,discount,discountprice,discounttotal,
				tax,taxprice,taxtotal,tax_total,comment,period,usedtype,redword,
				InvoiceTotal,InvoiceTag , PDetail, Dtypeid,bargainTotal,colorid,[convert],
				ifsupply,Costmode,SaleMoney,marketDiscount,marketDiscount1,vipdiscount,
				joincostprice,joincostTotal,branchid,packcode,packRate,packQty,Salemode,
				CustValue1,CustValue2, CustValue3, CustValue4, CustValue5, CustValue6,redold,
				billtype,Retailprice,unit,vipcardid,OPID,phrows,unitRate,singleunit)
			values(@nNewVchcode,@tDate,@nVchType,@szAtypeID,@szPtypeid,@szBtypeid,@szEtypeid,@szKtypeId,
				@dQty,@dPrice,@dTotal,@dcostPrice,@dcostTotal,@ddiscount,@ddiscountprice,@ddiscounttotal,
				@dtax,@dtaxprice,@dtaxtotal,@dtax_total,@szmemo,@period,@usedtype,'T',-@InvoiceTotal ,
				@InvoiceTag,@PDetail,@Dtypeid,@bargainTotal,@colorid,@convert,@ifsupply,
				@nCostMode,isnull(@SaleMoney,0),
				isnull(@marketDiscount,0),isnull(@marketDiscount1,0),
				isnull(@vipdiscount,100),isnull(@joincostprice,0),
				isnull(@JoinCostTotal,0),@Branchid,@packcode,@packRate,@packQty,@salemode,
				@CustValue1,@CustValue2,@CustValue3,@CustValue4,@CustValue5,@CustValue6,'T',
				@Billtype,@retailprice,@unit,@vipcardidT,@OPID,@Phrows,@unitRate,@singleunit)
			
			set @nDlyOrder = @@identity  
			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -9
				goto error
			end
			
			insert into DlydataDetail(DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],
        			DiscountTotal,CostTotal,Salemoney,JoinCostToTal,phrows,vchcode,usedtype) 
			select @nDlyOrder,sizeid,colorid,-qty,-1*(Total),-1*(Taxtotal),-1*(Tax_total),
        			-1*(BargainTotal),-1*([Convert]),-1*(DiscountTotal),-1*(CostTotal),
				-1*Salemoney,-1*JoinCostTotal,@Phrows,@nNewVchcode,usedtype from DlydataDetail where DlyOrder = @oDlyOrder
			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -9
				goto error
			end

			fetch next from CreateRed_cursor into @szatypeid, @szPtypeId,@szKtypeid,@dQty,@dPrice,@dTotal,
			@ddiscount,@ddiscountprice, @ddiscounttotal,@dtax,@dtaxprice,@dtaxtotal,@dtax_total,@dcostprice,
			@dcosttotal, @szmemo, @period,@usedtype,@oDlyOrder,@InvoiceTotal,@InvoiceTag ,@PDetail,
			@bargainTotal,@colorid,@convert,@ifSupply,@SaleMoney,@marketDiscount,@marketDiscount1,
			@vipdiscount,@Branchid,@salemode,@packcode,@packRate,@packQty,
			@CustValue1,@CustValue2, @CustValue3, @CustValue4,@CustValue5, @CustValue6,@JoinCostTotal,
			@Retailprice,@unit,@JoinCostPrice,@vipcardidT,@OPID,@Phrows,@unitRate,@singleunit
		end 	
		if @vchtypeList<>'' AND NOT @nVchType in (224,232) --处理订单(销售类)  --加盟配货，加盟退货只在出库方处理订单
		BEGIN
			update bakdlydetail set qty=-ABS(qty) where dlyorder in(select dlyorder from bakdly where  vchcode = @nNewVchcode)	
			update bakdly set qty=-ABS(qty) where  vchcode = @nNewVchcode

			exec @errorOrder=dbo.FZOrderCheck @nNewVchcode,0,@vchtypeList 	
			if @errorOrder<0
			BEGIN
				set @nRet=@errorOrder
				goto error
			END
			
		END	
		delete from bakdlydetail where DlyOrder in(select dlyorder from bakdly where  vchcode = @nNewVchcode )	
		delete from bakdly where vchcode = @nNewVchcode

		CLOSE CreateRed_cursor
		DEALLOCATE CreateRed_cursor
                
		
		-------------计算往来单位的当前可换货额----------------------------------------------------Begin
		SELECT TOP 1   @iniChange=iniChange,                  @nowChange=isnull(nowChange,0),
					   @LowLimitation=LowLimitation,		  @BarterTerm=BarterTerm,
					   @BarterRate=barterRate 
		From Btype Where typeid=@szBtypeid
		
		set @iniChange =isnull(@iniChange,0)
		set @nowChangeTem =isnull(@nowChangeTem,0)
		set @LowLimitation =isnull(@LowLimitation,0)
		set @BarterTerm =isnull(@BarterTerm,0)
		set @MarketDiscount =isnull(@MarketDiscount,0)
		set @BarterRate =isnull(@BarterRate,0)
		set @nowChange =isnull(@nowChange,0)
		--print @dTempTotal
		if @BarterRate<>0
		Begin 
		
			SELECT @dTax_Total=-1*(sum(Tax_total)) From Dlydata s,ptype p where s.usedtype=1 and s.redword='F' 
				and vchcode=@nVchcode and s.ptypeid=p.typeid and p.trade=1
		
			if @nVchType in(11,12,222)
			Begin
				if not  exists( Select * from btypechange where btypeid=@szbtypeid ) 
					set  @nowChangeTem =isnull(@iniChange,0) +isnull(@nowChange,0) - ((isnull(@dTax_Total,0)))* (isnull(@BarterRate,0)/100)
				else
					set  @nowChangeTem =isnull(@nowChange,0) - ((isnull(@dTax_Total,0)))* (isnull(@BarterRate,0)/100)
				
				set @cutchang=(isnull(@dTax_Total,0))*(isnull(@BarterRate,0)/100)
				set @Comment='红冲销售还原换货额'
				set @addChang=0
				exec  FZSetBtypeChange  @szBtypeid, @InputNo,@BarterRate,@BarterTerm,@nowChangeTem,0,@ddiscount,
		   		@addChang,@cutchang,@Comment,@LowLimitation,@MarketDiscount,@nowChangeTem
				update  btype set nowChange=isnull(@nowChangeTem,0) Where typeid=@szBtypeid
			End
			else if @nVchType in(45,13,224) and @BarterType=0
			Begin
				if not  exists( Select * from btypechange where btypeid=@szbtypeid ) 
					set  @nowChangeTem =isnull(@iniChange,0) + isnull(@nowChange,0) + ( abs(isnull(@dTax_Total,0)))
				else
					set  @nowChangeTem =isnull(@nowChange,0) + (abs(isnull(@dTax_Total,0)))
				set @addChang=abs(@dTax_Total)
				set @Comment='红冲销售退货还原换货额'
				set @cutchang=0
				exec  FZSetBtypeChange  @szBtypeid, @InputNo,@BarterRate,@BarterTerm,@nowChangeTem,0,@ddiscount,
		   		@addChang,@cutchang,@Comment,@LowLimitation,@MarketDiscount,@nowChangeTem
				update  btype set nowChange=@nowChangeTem Where typeid=@szBtypeid
			End
			if @nVchType=24 and @BarterType=0
			Begin
				set @Comment='红冲销售换货还原换货额'
				Declare @dTax_Total1 numeric(24,10)
				Declare @dTax_Total2 numeric(24,10)

				Select @dTax_Total1=abs(sum(Tax_total)) From Dlydata s,ptype p
					where usedtype=1 and redword='F' and vchtype=24 and vchcode=@nVchcode and s.ptypeid=p.typeid and p.trade=1
				Select @dTax_Total2=abs(sum(Tax_total)) From Dlydata s,ptype p
					where usedtype=2 and redword='F' and vchtype=24 and vchcode=@nVchcode and s.ptypeid=p.typeid and p.trade=1
			
				
			  	if not  exists( Select 1 from btypechange where btypeid=@szbtypeid ) 
				Begin
					set  @nowChangeTem =isnull(@iniChange,0) +isnull(@nowChange,0) + (isnull(@dTax_Total1,0))
					set @addChang=@dTax_Total1
					set @cutchang=0
					exec  FZSetBtypeChange  @szBtypeid, @InputNo,@BarterRate,@BarterTerm,@nowChangeTem,0,@ddiscount,
			   		@addChang,@cutchang,@Comment,@LowLimitation,@MarketDiscount,@nowChangeTem
					update  btype set nowChange=@nowChangeTem Where typeid=@szBtypeid
				End
				else
				Begin
					set  @nowChangeTem =isnull(@nowChange,0) + (isnull(@dTax_Total1,0))
					set @addChang=@dTax_Total1
					set @cutchang=0
					exec  FZSetBtypeChange  @szBtypeid, @InputNo,@BarterRate,@BarterTerm,@nowChangeTem,0,@ddiscount,
			   		@addChang,@cutchang,@Comment,@LowLimitation,@MarketDiscount,@nowChangeTem
					update  btype set nowChange=@nowChangeTem Where typeid=@szBtypeid
				End
				SELECT TOP 1 @iniChange=iniChange,@nowChange=isnull(nowChange,0),@LowLimitation=LowLimitation,
			      		@BarterTerm=BarterTerm,@BarterRate=barterRate 
			        From Btype Where typeid=@szBtypeid
				if not  exists( Select 1 from btypechange where btypeid=@szbtypeid ) 
				Begin
					set  @nowChangeTem =isnull(@iniChange,0) +isnull(@nowChange,0) - (isnull(@dTax_Total2,0))* (isnull(@BarterRate,0)/100)
					set @CutChang=isnull(@dTax_Total2* (@BarterRate/100),0)
					set @addChang=0
					exec  FZSetBtypeChange  @szBtypeid, @InputNo,@BarterRate,@BarterTerm,@nowChangeTem,0,@ddiscount,
			   		@addChang,@cutchang,@Comment,@LowLimitation,@MarketDiscount,@nowChangeTem
					update  btype set nowChange=@nowChangeTem Where typeid=@szBtypeid
				End
				else
				Begin
					set  @nowChangeTem =isnull(@nowChange,0) - (isnull(@dTax_Total2,0))* (isnull(@BarterRate,0)/100)
					set @CutChang=isnull((@dTax_Total2)* (@BarterRate/100),0)
					set @addChang=0
					exec  FZSetBtypeChange  @szBtypeid, @InputNo,@BarterRate,@BarterTerm,@nowChangeTem,0,@ddiscount,
			   		@addChang,@cutchang,@Comment,@LowLimitation,@MarketDiscount,@nowChangeTem
					update  btype set nowChange=isnull(@nowChangeTem,0) Where typeid=@szBtypeid
				End
			End
		End
		if (@TRANSFLAG<>'TRANSFER') and @nVchType in(11,12,13,45,222,224,100,101,24,226,227)--处理VIp消费金额和vip积分
		Begin
	        declare @tmpRet int

			IF @nVchType IN (12,100)--零售单,专柜零售单
			BEGIN
				Select @execsql='declare Vip_crusor cursor  FORWARD_ONLY STATIC READ_ONLY for '
							+' SELECT Distinct  VipCardID '
							+'   FROM DlyData '
							+'   Where Vchcode= '+CAST(@nVchcode AS varchar(10))
							+'   and vipcardid<>'''' '
				exec (@execsql)
				OPEN Vip_crusor
				fetch next from Vip_crusor into @VipCardID 
			 	while @@FETCH_STATUS=0	
				BEGIN
						    exec @tmpRet=FZWriteIntegralDetailForRed @VIPCardID,@szktypeid,@NnewVchcode,@nvchcode,@szGeneralTotal output
				            if @tmpRet<>0  goto error
						    set @RetTotalSaleMoney=-@TotalSaleMoney
						    set @RetTotalJFJE=-@TotalJFJE
						    set @RetVipCardId=@VIPCardID
					fetch next from Vip_crusor into @VipCardID 
				END
				CLOSE Vip_crusor
				DEALLOCATE Vip_crusor

			END
			ELSE
			BEGIN
			    exec @tmpRet=FZWriteIntegralDetailForRed @VIPCardID,@szktypeid,@NnewVchcode,@nvchcode,@szGeneralTotal output
		            if @tmpRet<>0  goto error
			    set @RetTotalSaleMoney=-@TotalSaleMoney
			    set @RetTotalJFJE=-@TotalJFJE
			    set @RetVipCardId=@VIPCardID
			END
	 	End
	end
	else
	if @nVchType in (34,6,73,28)
	begin
		
		select @execsql='declare CreateRed_cursor cursor FORWARD_ONLY STATIC READ_ONLY for '
		+' select atypeid, ptypeid, ktypeid, qty, price, total, discount, discountprice, discounttotal, 
		tax, taxprice, taxtotal, tax_total, costprice, costtotal, comment, period, usedtype, 
		DlyOrder,InvoiceTotal , InvoiceTag , PDetail,bargainTotal,colorid,'+
		'[convert],ifsupply,branchid,packcode,packRate,packQty,
		CustValue1,CustValue2, CustValue3, CustValue4, CustValue5,'+
		' CustValue6,salemoney,Retailprice,unit,opid,phrows,unitRate,singleunit from DlyData  '+
		 'where Vchcode= '+CAST(@nVchcode AS varchar(10)) +' order by dlyorder'
	
		exec (@execsql)	
		
		OPEN CreateRed_cursor
		fetch next from CreateRed_cursor into @szatypeid, @szPtypeId,@szKtypeid, @dQty,@dPrice,@dTotal,
		@ddiscount,@ddiscountprice, @ddiscounttotal,@dtax,@dtaxprice,@dtaxtotal,@dtax_total,@dcostprice,
		@dcosttotal,@szmemo, @period,@usedtype,@oDlyOrder,@InvoiceTotal ,@InvoiceTag , @PDetail,
		@bargainTotal,@colorid,@convert,@ifsupply,@Branchid,@packcode,@packRate,@packQty,
		@CustValue1,@CustValue2, @CustValue3, @CustValue4, @CustValue5, @CustValue6,
		@SaleMoney,@Retailprice,@unit,@OPID,@Phrows,@unitRate,@singleunit 
		while @@FETCH_STATUS=0
		begin
			
			set @dQty = -1*isnull(@dQty,0)
			set @dTaxTotal = -1*isnull(@dTaxTotal,0)
			set @dTax_Total = -1*isnull(@dTax_Total,0)
			set @dCostTotal = -1* isnull(@dCostTotal,0)	
			set @dTotal = -1*isnull(@dTotal,0)
			set @dDiscountTotal = -1*isnull(@dDiscountTotal,0)
			set @bargainTotal=-1*isnull(@bargainTotal,0)
			set @convert=-1*isnull(@convert,0)
			set @SaleMoney=-1*isnull(@SaleMoney,0)
			--增加红冲草稿
			if @szPtypeId<>'' 
			begin
				SELECT TOP 1  @nCostmode=costmode from ptype where typeid=@szptypeid
			end	

			insert into bakdly(vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				    qty,price,total,costprice,costtotal,discount,discountprice,discounttotal,
				tax,taxprice,taxtotal,tax_total,comment,period,usedtype,
				bargainTotal,colorid,[convert],ifsupply,
				branchid,packcode,packRate,packQty,costmode,
				CustValue1,CustValue2, CustValue3, CustValue4, CustValue5,
				CustValue6,billtype,SaleMoney,Retailprice,unit,phrows,unitRate,singleunit)
			values(@nNewVchcode,@tDate,@nVchType,@szAtypeID,@szPtypeid,@szBtypeid,@szEtypeid,@szKtypeId,
				@dQty,@dPrice,@dTotal,@dcostPrice,@dcostTotal,@ddiscount,@ddiscountprice,@ddiscounttotal,
				@dtax,@dtaxprice,@dtaxtotal,@dtax_total,@szmemo,@period,@usedtype,
				@bargainTotal,@colorid,@convert,@ifsupply,@Branchid,
				@packcode,@packRate,@packQty,@ncostmode,
				@CustValue1,@CustValue2,@CustValue3,@CustValue4,@CustValue5,@CustValue6,@Billtype,
				@SaleMoney,@Retailprice,@unit,@phrows,@unitRate,@singleunit)		
            	
			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -9
				goto error
			end
            SET @cDlyOrder = @@identity 
            insert into bakdlydetail (DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],
                			DiscountTotal,CostTotal,salemoney,phrows,vchcode,usedtype) 
            select @cDlyOrder,sizeid,colorid,ABS(QTY),ABS(Total),ABS(Taxtotal),ABS(Tax_total),
                			ABS(BargainTotal),ABS([Convert]),ABS(DiscountTotal),ABS(CostTotal),
					abs(SaleMoney),@phrows,@nNewVchcode,usedtype 
			from DlydataDetail 
			where DlyOrder = @oDlyOrder
			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -9
				goto error
			end
                                        --add end
			if @szPtypeId<>'' 
			begin
				
				if @dcostTotal=0 and @nCostmode=0 set @ncostmode=4
				set @ncostmode=ISNULL(@ncostmode,0)
				if @szKtypeid in (@SEND_GOODS_STOCK_ID,@COMMISSION_STOCK_ID,@RECOMMISSION_STOCK_ID)
					Exec @nRet = FZModifyDbfCom @nVchtype,@nCostmode,@szptypeid,@szBtypeid,
					@dqty,@dTax_total,@dcosttotal,@type,@dTemp output,@dTemp1 output,@cDlyOrder
				else		
					Exec @nRet = FZModifyDbf @nVchtype,@nCostmode,@GOODs_ID,@szptypeid,'',@szktypeid,
					@period,@dqty,@dcosttotal,@dTemp output,@cDlyOrder,@branchid
			end
			else
			begin		
				Exec @nRet = FZModifyDbf @nVchtype,@nCostmode,@szAtypeId,@szptypeid,@szBtypeId,
					@szktypeid,@period,@dqty,@dTotal,@dTemp output,@cDlyOrder,@branchid
			end
			if @nRet<0 goto error
			--处理补货标志
			if exists(Select 1 From BtypeSupply Where btypeid=@szbtypeid and ptypeid=@szptypeid and colorid=@colorid) and @nVchType=34
			Begin
			 	
				if not exists(Select s.vchcode From Dlydata s,dlyndx d Where d.vchcode=s.vchcode 
			   					and s.btypeid=@szbtypeid and s.ptypeid=@szptypeid and d.VchType=34
			   					and d.draft not in(1,4,8,10,3) and d.redold<>'T' 
								and colorid=@colorid )
				BEGIN
					Delete From BtypeSupply where btypeid=@szBtypeid and ptypeid=@szptypeid and colorid=@colorid
				END
				else
				Begin   
				   	if not exists(Select s.vchcode From Dlydata s,dlyndx d Where d.vchcode=s.vchcode 
			   		and s.btypeid=@szbtypeid and s.ptypeid=@szptypeid and d.VchType=34
			   		and d.draft not in(1,4,8,10,3)and d.redold<>'T' 
					and colorid=@colorid and s.ifSupply=1)
					Update BtypeSupply
						Set ifSupply =0 
					Where btypeid=@szBtypeid and ptypeid=@szptypeid and colorid=@colorid
				end
			
			End
	
			
		
			insert into dlydata(vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				qty,price,total,costprice,costtotal,discount,discountprice,discounttotal,
				tax,taxprice,taxtotal,tax_total,comment,period,usedtype,redword, 
				InvoiceTotal ,InvoiceTag , PDetail, Dtypeid,bargainTotal,colorid,[convert],ifsupply,
				branchid,packcode,packRate,packQty,CustValue1,CustValue2, CustValue3, CustValue4, CustValue5, CustValue6
				,redold,Billtype,SaleMoney,Retailprice,unit,opid,phrows,unitRate,singleunit)
			values(@nNewVchcode,@tDate,@nVchType,@szAtypeID,@szPtypeid,@szBtypeid,@szEtypeid,@szKtypeId,
				@dQty,@dPrice,@dTotal,@dcostPrice,@dcostTotal,@ddiscount,@ddiscountprice,@ddiscounttotal,
				@dtax,@dtaxprice,@dtaxtotal,@dtax_total,@szmemo,@period,@usedtype,'T',
				-@InvoiceTotal , @InvoiceTag , @PDetail , @Dtypeid,@bargainTotal,
				@colorid,@convert,@ifsupply,@Branchid,@packcode,@packRate,@packQty,
				@CustValue1,@CustValue2, @CustValue3, @CustValue4, @CustValue5, @CustValue6,'T',@Billtype,
				@SaleMoney,@Retailprice,@unit,@OPID,@phrows,@unitRate,@singleunit)	
 			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -6
				goto error
			END
			set @nDlyOrder = @@identity 
			if @nVchType =6 
				insert into DlydataDetail(DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],
        			DiscountTotal,CostTotal,SaleMoney,phrows,vchcode,usedtype) 
				select @nDlyOrder,sizeid,colorid,-qty,ABS(Total),ABS(Taxtotal),ABS(Tax_total),
        			ABS(BargainTotal),ABS([Convert]),ABS(DiscountTotal),ABS(CostTotal),
				Abs(SaleMoney),@phrows,@nNewVchcode,usedtype from DlydataDetail where DlyOrder = @oDlyOrder		
			else
				insert into DlydataDetail(DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],
	        			DiscountTotal,CostTotal,SaleMoney,phrows,vchcode,usedtype) 
				select @nDlyOrder,sizeid,colorid,-qty,-ABS(Total),-ABS(Taxtotal),-ABS(Tax_total),
	        			-ABS(BargainTotal),-ABS([Convert]),-ABS(DiscountTotal),-ABS(CostTotal),
				-Abs(SaleMoney),@phrows,@nNewVchcode,usedtype from DlydataDetail where DlyOrder = @oDlyOrder				
			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -5
				goto error
			end

			fetch next from CreateRed_cursor into @szatypeid, @szPtypeId,@szKtypeid, @dQty,@dPrice,@dTotal,
			@ddiscount,@ddiscountprice, @ddiscounttotal,@dtax,@dtaxprice,@dtaxtotal,@dtax_total,@dcostprice,
			@dcosttotal,@szmemo, @period,@usedtype,@oDlyOrder,@InvoiceTotal ,@InvoiceTag , @PDetail,
			@bargainTotal,@colorid,@convert,@ifsupply,@Branchid,@packcode,@packRate,@packQty,
			@CustValue1,@CustValue2,@CustValue3,@CustValue4,@CustValue5,@CustValue6,@SaleMoney,@Retailprice
			,@unit,@OPID,@phrows,@unitRate,@singleunit 
			
		End
		
		if @vchtypeList<>'' --处理订单（进货）
		begin
			
			update bakdlydetail set qty=-ABS(qty) where dlyorder in(select dlyorder from bakdly where  vchcode = @nNewVchcode)	
			update bakdly set qty=-ABS(qty) where  vchcode = @nNewVchcode	

			exec @errorOrder=dbo.FZOrderCheck @nNewVchcode,0,@vchtypeList 	
 		        if @errorOrder<0
			BEGIN
				set @nRet=@errorOrder
				goto error
			END
		END	
		
		delete from bakdlydetail where DlyOrder in(select dlyorder from bakdly where  vchcode = @nNewVchcode )	
		delete from bakdly where vchcode = @nNewVchcode
		CLOSE CreateRed_cursor
		DEALLOCATE CreateRed_cursor

	

		-------------计算往来单位的当前可换货额----------------------------------------------------Begin
		SELECT TOP 1 @iniChange=iniChange,            @nowChange=isnull(nowChange,0),
			   @LowLimitation=LowLimitation, 		  @BarterTerm=BarterTerm,
			   @BarterRate=barterRate 
		From Btype Where typeid=@szBtypeid
		
		set @iniChange =isnull(@iniChange,0)
		set @nowChangeTem =isnull(@nowChangeTem,0)
		set @LowLimitation =isnull(@LowLimitation,0)
		set @BarterTerm =isnull(@BarterTerm,0)
		set @MarketDiscount =isnull(@MarketDiscount,0)
		set @BarterRate =isnull(@BarterRate,0)
		set @nowChange =isnull(@nowChange,0)
	
        SELECT  @dTax_Total = ABS(SUM(ISNULL(b.Tax_total, 0)))
        FROM    dlydata b ,
                ptype p
        WHERE   usedtype = 1
                AND redword = 'F'
                AND vchcode = @nVchcode
                AND b.ptypeid = p.typeid
                AND p.trade = 1
	
		if @BarterRate<>0
		Begin 
			if @nVchType=34
			Begin
				if not exists( Select 1 from btypechange where btypeid=@szbtypeid ) 
					set  @nowChangeTem =isnull(@iniChange,0) +isnull(@nowChange,0) - ( abs(isnull(@dTax_Total,0)))* (@BarterRate/100)
				else
					set  @nowChangeTem =isnull(@nowChange,0) - (abs(isnull(@dTax_Total,0)))* (isnull(@BarterRate,0)/100)
				set @cutChang=isnull(abs(isnull(@dTax_Total,0) *(@BarterRate/100)),0)
				set @Comment='红冲进货还原换货额'
				set @addChang=0
				exec  FZSetBtypeChange  @szBtypeid, @InputNo,@BarterRate,@BarterTerm,@nowChangeTem,0,@ddiscount,
		   		@addChang,@cutChang,@Comment,@LowLimitation,@MarketDiscount,@nowChangeTem
				update  btype set nowChange=@nowChangeTem Where typeid=@szBtypeid
			End
			if @nVchType=6 and @BarterType=0
			Begin
				if not exists( Select 1 from btypechange where btypeid=@szbtypeid ) 
					set  @nowChangeTem =isnull(@iniChange,0) +isnull(@nowChange,0) + ( abs(isnull(@dTax_Total,0)))
				else
					set  @nowChangeTem =isnull(@nowChange,0) + (abs(isnull(@dTax_Total,0)))
				set @addChang=abs(@dTax_Total)
				set @Comment='红冲进货退货还原换货额'
				set @cutChang=0
				exec  FZSetBtypeChange  @szBtypeid, @InputNo,@BarterRate,@BarterTerm,@nowChangeTem,0,@ddiscount,
		   		@addChang,@cutChang,@Comment,@LowLimitation,@MarketDiscount,@nowChangeTem
				update  btype set nowChange=@nowChangeTem Where typeid=@szBtypeid
			End
		End
----------------------------------------------------------------------------------------------------------------------
	end
	else if @nVchType in (140,141,142,143)
	begin
		select @execsql='declare CreateRed_cursor cursor FORWARD_ONLY STATIC READ_ONLY for '
				+' select atypeid, ptypeid, ktypeid,qty, price, total, discount, discountprice, discounttotal, 
				tax, taxprice, taxtotal, tax_total, costprice, costtotal, comment, period, usedtype, 
				DlyOrder, InvoiceTotal , InvoiceTag , PDetail,bargainTotal,colorid,[convert],branchid,costmode,
				CustValue1,CustValue2, CustValue3, CustValue4, CustValue5, CustValue6,
				SaleMoney,Retailprice,unit,opid,unitRate,singleunit from dlydata
				 where Vchcode= '+CAST(@nVchcode AS varchar(10)) +' order by dlyorder'
		exec (@execsql)
		OPEN CreateRed_cursor
		fetch next from CreateRed_cursor into @szatypeid, @szPtypeId,@szKtypeid,@dQty,@dPrice,@dTotal,
			  @ddiscount,@ddiscountprice, @ddiscounttotal,@dtax,@dtaxprice,@dtaxtotal,@dtax_total,@dcostprice,
			 @dcosttotal,@szmemo, @period, @usedtype,@oDlyOrder, @InvoiceTotal , @InvoiceTag , @PDetail,
			 @bargainTotal,@colorid,@convert,@Branchid,@ncostmode,@CustValue1,@CustValue2,@CustValue3, 
			 @CustValue4,@CustValue5,@CustValue6,@SaleMoney,@Retailprice,@unit,@OPID,@unitRate,@singleunit
			
		while @@FETCH_STATUS=0
		begin
			--print 'ok,,,,'
				set @dQty = -1*@dQty
				set @dCostTotal = -1* @dCostTotal	
				set @dTaxTotal = -1*@dTaxTotal
				set @dTax_Total = -1*@dTax_Total
				set @dTotal = -1*@dTotal
				set @dDiscountTotal = -1*@dDiscountTotal
				set @bargainTotal=-@bargainTotal
				set @convert=-@convert
				
			--增加红冲草稿
			if @dCostTotal=0 and @ncostmode=0 set @ncostmode=4

			insert into bakdly(vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				qty,price,total,costprice,costtotal,discount,discountprice,discounttotal,tax,taxprice,
				taxtotal,tax_total,comment,period,usedtype,bargainTotal,colorid,
				[convert],branchid,costmode,
				CustValue1,CustValue2, CustValue3, CustValue4, CustValue5, CustValue6,Billtype,
				SaleMoney,Retailprice,unit,unitRate,singleunit)
			values(@nNewVchcode,@tDate,@nVchType,@szAtypeID,@szPtypeid,@szBtypeid,@szEtypeid,@szKtypeId,
				@dQty,@dPrice,@dTotal,@dcostPrice,@dcostTotal,@ddiscount,@ddiscountprice,@ddiscounttotal,
				@dtax,@dtaxprice,@dtaxtotal,@dtax_total,@szmemo,@period,@usedtype,
				@bargainTotal,@colorid,@convert,@Branchid,ISNULL(@ncostmode,0),
				@CustValue1,@CustValue2, @CustValue3,@CustValue4,@CustValue5,@CustValue6,@Billtype,
				@SaleMoney,@Retailprice,@unit,@unitRate,@singleunit)	
              
			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -9
				goto error
			end
		    set @cDlyOrder = @@identity 
            insert into bakdlydetail (DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],
        			DiscountTotal,CostTotal,SaleMoney) 
        	select @cDlyOrder,sizeid,colorid,ABS(QTY),ABS(Total),ABS(Taxtotal),ABS(Tax_total),
        			ABS(BargainTotal),ABS([Convert]),ABS(DiscountTotal),ABS(CostTotal),
				ABs(SaleMoney) 
			from DlydataDetail 
			where DlyOrder = @oDlyOrder
			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -9
				goto error
			end
			                                    
			if @szPtypeId<>'' 
			begin
				
				Exec @nRet = FZModifyDbf @nVchtype,@nCostmode,@GOODs_ID,@szptypeid,'',@szktypeid,
					@period,@dqty,@dcosttotal,@dTemp output,@cDlyOrder,@branchid
					--print 'ccl'
			end
			else
			begin				
				Exec @nRet = FZModifyDbf @nVchtype,@nCostmode,@szAtypeId,@szptypeid,@szBtypeId,@szktypeid,
				@period,@dqty,@dTotal,@dTemp output,@cDlyorder,@branchid
			end
			--if @nVchType=144 Select @dqty=0
			if @nRet<0 goto error
			insert into dlydata(vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				qty,price,total,costprice,costtotal,discount,discountprice,discounttotal,tax,taxprice,
				taxtotal,tax_total,comment,period,usedtype,redword, InvoiceTotal,
				InvoiceTag ,PDetail, Dtypeid,bargainTotal,colorid,[convert],branchid,
				CustValue1,CustValue2, CustValue3, CustValue4, CustValue5, CustValue6,redold,Billtype,
				SaleMoney,Retailprice,unit,opid,unitRate,singleunit)
			values( @nNewVchcode,@tDate,@nVchType,@szAtypeID,@szPtypeid,@szBtypeid,@szEtypeid,@szKtypeId,
				@dQty,@dPrice,@dTotal,@dcostPrice,@dcostTotal,@ddiscount,@ddiscountprice,
				@ddiscounttotal,@dtax,@dtaxprice,@dtaxtotal,@dtax_total,@szmemo,
				@period,@usedtype,'T', -@InvoiceTotal,@InvoiceTag,@PDetail,@Dtypeid,@bargainTotal,
			       @colorid,@convert,@Branchid,@CustValue1,@CustValue2,@CustValue3,@CustValue4,
			       @CustValue5,@CustValue6,'T',@Billtype,@SaleMoney,@Retailprice,@unit,@OPID,@unitRate,@singleunit)	
               
			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -9
				
				goto error
			END
			set @nDlyOrder = @@identity
			insert into DlydataDetail(DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],
        			DiscountTotal,CostTotal,SaleMoney) 
			select @nDlyOrder,sizeid,colorid,-qty,-(Total),-(Taxtotal),-(Tax_total),
        			-(BargainTotal),-([Convert]),-(DiscountTotal),-(CostTotal),
				-(SaleMoney)  from DlydataDetail where DlyOrder = @oDlyOrder				
			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -9
				goto error
			end
			--删除草稿
			delete from bakdlydetail where dlyorder=@cDlyOrder
		
			fetch next from CreateRed_cursor into @szatypeid, @szPtypeId,@szKtypeid,@dQty,@dPrice,@dTotal,
			  @ddiscount,@ddiscountprice, @ddiscounttotal,@dtax,@dtaxprice,@dtaxtotal,@dtax_total,@dcostprice,
			 @dcosttotal,@szmemo, @period, @usedtype,@oDlyOrder, @InvoiceTotal , @InvoiceTag , @PDetail,
			 @bargainTotal,@colorid,@convert,@Branchid,@ncostmode,@CustValue1,@CustValue2,@CustValue3, 
			 @CustValue4,@CustValue5,@CustValue6,@SaleMoney,@Retailprice,@unit,@OPID,@unitRate,@singleunit
			
			delete from bakdly where vchcode=@nNewVchcode
		end 
		CLOSE CreateRed_cursor
		DEALLOCATE CreateRed_cursor
	end
	else
	begin
		--赠送单 删除唯一码
		--if @nVchtype = 139
		--	delete from PtypeUniqueCode where vchcode=@nVchcode
	
		select @execsql='declare CreateRed_cursor cursor FORWARD_ONLY STATIC READ_ONLY for '
				+' select atypeid, ptypeid, ktypeid,qty, price, total, discount, discountprice, discounttotal, 
				tax, taxprice, taxtotal, tax_total, costprice, costtotal,comment, period, usedtype, 
				DlyOrder, InvoiceTotal , InvoiceTag , PDetail,bargainTotal,colorid,[convert],branchid
				,CustValue1,CustValue2, CustValue3, CustValue4, CustValue5, CustValue6,SaleMoney,Retailprice,'+
				'  unit,opid,phrows,unitRate,singleunit from dlydata
				 where Vchcode= '+CAST(@nVchcode AS varchar(10))+' order by dlyorder'
		
		exec (@execsql)
		OPEN CreateRed_cursor
		fetch next from CreateRed_cursor into @szatypeid, @szPtypeId,@szKtypeid, @dQty,@dPrice,@dTotal,
			  @ddiscount,@ddiscountprice, @ddiscounttotal,@dtax,@dtaxprice,@dtaxtotal,@dtax_total,
			  @dcostprice, @dcosttotal, @szmemo, @period, @usedtype,@oDlyOrder,
			 @InvoiceTotal,@InvoiceTag ,@PDetail,@bargainTotal,@colorid,@convert,@Branchid,
			 @CustValue1,@CustValue2,@CustValue3,@CustValue4,@CustValue5,@CustValue6,@SaleMoney,
			 @Retailprice,@unit,@OPID,@phrows,@unitRate,@singleunit
		while @@FETCH_STATUS=0
		begin
 			
			if @nVchtype in (50,51)
			Begin
				set @dTax_Total = -1*@dTax_Total
				set @bargainTotal=-1*@bargainTotal
				set @dTotal = -1*@dTotal
				set @dDiscountTotal = -1*@dDiscountTotal
			End
			else
			Begin
				set @dQty = -1*@dQty
				set @dCostTotal = -1* @dCostTotal	
				set @dTaxTotal = -1*@dTaxTotal
				set @dTax_Total = -1*@dTax_Total
				set @dTotal = -1*@dTotal
				set @dDiscountTotal = -1*@dDiscountTotal
				set @bargainTotal=-@bargainTotal
				set @convert=-@convert
			End
			--增加红冲草稿
			if @szPtypeId<>'' 
			begin
				SELECT TOP 1 @nCostmode=costmode from ptype where typeid=@szptypeid	
			end
			if @dCostTotal=0 and @nCostmode=0 and @nVchType not in(150,144) set @nCostmode=4
			insert into bakdly(vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				qty,price,total,costprice,costtotal,discount,discountprice,discounttotal,tax,taxprice,
				taxtotal,tax_total,comment,period,usedtype,bargainTotal,colorid,
				[convert],branchid,CostMode,CustValue1,CustValue2,CustValue3,
				CustValue4,CustValue5,CustValue6,Billtype,SaleMoney,Retailprice,unit,phrows,unitRate,singleunit)
			values(@nNewVchcode,@tDate,@nVchType,@szAtypeID,@szPtypeid,@szBtypeid,@szEtypeid,@szKtypeId,
				@dQty,@dPrice,@dTotal,@dcostPrice,@dcostTotal,@ddiscount,@ddiscountprice,@ddiscounttotal,
				@dtax,@dtaxprice,@dtaxtotal,@dtax_total,@szmemo,@period,@usedtype,
				@bargainTotal,@colorid,@convert,@Branchid,ISNULL(@nCostmode,0),
				@CustValue1,@CustValue2,@CustValue3,@CustValue4,@CustValue5,@CustValue6,@Billtype,
				@SaleMoney,@Retailprice,@unit,@phrows,@unitRate,@singleunit)		
                        set @cDlyOrder = @@identity  
			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -9
				goto error
			end

			if @nVchType in(150,144) 
                insert into bakdlydetail(DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],
	        			DiscountTotal,CostTotal,SaleMoney,phrows,Vchcode,usedtype) 
				select @cDlyOrder,sizeid,colorid,-qty,-(Total),-(Taxtotal),-(Tax_total),
	        			-(BargainTotal),-([Convert]),-(DiscountTotal),-(CostTotal),-(SaleMoney),@phrows,@nNewVchcode,usedtype 
				from DlydataDetail 
				where DlyOrder = @oDlyOrder				
			else			
                insert into bakdlydetail(DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],
	        			DiscountTotal,CostTotal,SaleMoney,phrows,Vchcode,usedtype) 
				select @cDlyOrder,sizeid,colorid,ABS(qty),ABS(Total),ABS(Taxtotal),ABS(Tax_total),
	        			ABS(BargainTotal),ABS([Convert]),ABS(DiscountTotal),ABS(CostTotal),
					ABS(SaleMoney),@phrows,@nNewVchcode,usedtype 	
				from DlydataDetail 
				where DlyOrder = @oDlyOrder		
						
			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -9
				goto error
			end
			
			if @szPtypeId<>'' 
			begin
				--select @nCostmode=costmode from ptype where typeid=@szptypeid	
				if @szKtypeid in (@SEND_GOODS_STOCK_ID,@COMMISSION_STOCK_ID,@RECOMMISSION_STOCK_ID)
				begin
					if @nVchtype in (50,51)
					begin
						set @dQty=0
						set @dCosttotal=0
					end
					Exec @nRet = FZModifyDbfCom @nVchtype,@nCostmode,@szptypeid,@szBtypeid,
					@dqty,@dTax_total,@dcosttotal,@type,@dTemp output,@dTemp1 output,@cDlyOrder
				end
				else			
				Begin
					if @nVchType in(150,144) 
					Begin
						set @dcosttotal=@dcostPrice
						if @nCostmode<>0
						Begin
							Select @dqty=sum(isnull(qty,0)) from bakdlydetail where dlyorder= @cDlyOrder and qty<0
							exec  @nRet = FZModifyDbf @nVchType,@nCostmode,@GOODs_ID,@szptypeid,@szbtypeid,@szktypeid,
							@period,@dqty,0,@dTemp out,@cDlyOrder,@branchid
							if @nRet<0 goto error
							
							set @DTemp=abs(@dTemp)
							Select @dqty=sum(isnull(qty,0)) from bakdlydetail where dlyorder= @cDlyOrder and qty>0
							exec  @nRet = FZModifyDbf @nVchType,@nCostmode,@GOODs_ID,@szptypeid,@szbtypeid,@szktypeid,
							@period,@dqty,@dTemp,@dTemp out,@cDlyOrder,@branchid
							if @nRet<0 goto error	
						End
						else
						Begin
							exec  @nRet = FZModifyDbf @nVchType,@nCostmode,@GOODs_ID,@szptypeid,@szbtypeid,@szktypeid,
							@period,0,0,@dTemp out,@cDlyOrder,@branchid
							if @nRet<0 goto error
						End
					End
					else 
					Begin
						Exec @nRet = FZModifyDbf @nVchtype,@nCostmode,@GOODs_ID,@szptypeid,'',@szktypeid,
						@period,@dqty,@dcosttotal,@dTemp output,@cDlyOrder,@branchid
					end
					--print 'ccl'
				End
			
			end
			else
			begin				
				Exec @nRet = FZModifyDbf @nVchtype,@nCostmode,@szAtypeId,@szptypeid,@szBtypeId,@szktypeid,
				@period,@dqty,@dTotal,@dTemp output,@cDlyorder,@branchid
			end
			if  @nVchType in(150,144)  set @dqty=0
			if @nRet<0 goto error

			insert into dlydata(vchcode,Date,vchType,atypeid,ptypeid,btypeid,etypeid,ktypeid,
				qty,price,total,costprice,costtotal,discount,discountprice,discounttotal,tax,taxprice,
				taxtotal,tax_total,comment,period,usedtype,redword, InvoiceTotal,
				InvoiceTag ,PDetail, Dtypeid,bargainTotal,colorid,[convert],branchid,
				CustValue1,CustValue2, CustValue3, CustValue4, CustValue5, CustValue6,redold,Billtype,
				SaleMoney,Retailprice,unit,opid,phrows,unitRate,singleunit)
			values( @nNewVchcode,@tDate,@nVchType,@szAtypeID,@szPtypeid,@szBtypeid,@szEtypeid,@szKtypeId,
				@dQty,@dPrice,@dTotal,@dcostPrice,case when @nvchtype in(150,144) 
				 then 0 else @dcostTotal end,@ddiscount,@ddiscountprice,
				@ddiscounttotal,@dtax,@dtaxprice,@dtaxtotal,@dtax_total,@szmemo,
				@period,@usedtype,'T', -@InvoiceTotal,@InvoiceTag,@PDetail,@Dtypeid,@bargainTotal,
				@colorid,@convert,@Branchid,
				@CustValue1,@CustValue2,@CustValue3,@CustValue4,@CustValue5,@CustValue6,'T',@Billtype,
				@SaleMoney,@Retailprice,@unit,@OPID,@phrows,@unitRate,@singleunit)	
		        
			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -9
				goto error
			END
			set @nDlyOrder = @@identity 
			insert into DlydataDetail(DlyOrder,SIZEID,COLORID,QTY,Total,Taxtotal,Tax_total,BargainTotal,[Convert],
        			DiscountTotal,CostTotal,SaleMoney,phrows,Vchcode,usedtype) 
			select @nDlyOrder,sizeid,colorid,-qty,-(Total),-(Taxtotal),-(Tax_total),
        			-(BargainTotal),-([Convert]),-(DiscountTotal),-(CostTotal),
				-(SaleMoney),@phrows,@nNewVchcode,usedtype 	
			from DlydataDetail 
			where DlyOrder = @oDlyOrder				
			
			if @@rowcount <=0 or @@Error <> 0 
			begin
				set @nRet = -9
				goto error
			end
                                        --add end
			delete from bakdlydetail where DlyOrder = @cDlyOrder
			
			fetch next from CreateRed_cursor into @szatypeid, @szPtypeId,@szKtypeid, @dQty,@dPrice,@dTotal,
			  @ddiscount,@ddiscountprice, @ddiscounttotal,@dtax,@dtaxprice,@dtaxtotal,@dtax_total,
			  @dcostprice, @dcosttotal, @szmemo, @period, @usedtype,@oDlyOrder,
			  @InvoiceTotal,@InvoiceTag ,@PDetail,@bargainTotal,@colorid,@convert,@Branchid,
			  @CustValue1,@CustValue2,@CustValue3,@CustValue4,@CustValue5,@CustValue6,
			  @SaleMoney,@Retailprice,@unit,@OPID,@phrows,@unitRate,@singleunit
			
			delete from bakdly where vchcode = @nNewVchcode
		end 
		
		update dlydata set dlydata.qty=(Select sum(qty) From dlydatadetail where  
			dlyorder in(Select dlyorder From dlydata where dlydata.vchcode=@nNewVchcode 
			and dlydata.vchtype in(50,51))) 
		where dlydata.vchcode= @nNewVchcode and dlydata.vchtype in(50,51)	
	
		
		CLOSE CreateRed_cursor
		DEALLOCATE CreateRed_cursor
	end
	
	select @execsql='declare CreateRed_cursor cursor FORWARD_ONLY STATIC READ_ONLY for '
		+' select atypeid, btypeid, total, comment, period, usedtype,InvoiceTotal , InvoiceTag,branchid from dlya '
		+'where Vchcode= '+CAST(@nVchcode AS varchar(10)) +' order by dlyorder'
	
	
	exec (@execsql)
	OPEN CreateRed_cursor
	fetch next from CreateRed_cursor into @szatypeid, @szBtypeid, @dTotal, @szmemo, @period, @usedtype, @InvoiceTotal ,
	@InvoiceTag,@Branchid
	while @@FETCH_STATUS=0
	begin
		set @dTotal = -1*@dTotal
		Exec @nRet = FZModifyDbf @nVchtype,@nCostmode,@szAtypeId,'',@szBtypeId,@szktypeid,
			@period,@dTotal,@dTotal,@dTemp output,@nDlyOrder,@branchid
-- 		print @nRet
-- 		print 'koko'
		if @nRet<0 goto error

		insert into dlya(vchcode,Date,vchType,atypeid,btypeid,etypeid,ktypeid,
			    total,comment,period,usedtype,redword,InvoiceTotal , InvoiceTag , Dtypeid,branchid,redold,billtype)
		values(@nNewVchcode,@tDate,@nVchType,@szAtypeID,@szBtypeid,@szEtypeid,@szKtypeId,
			@dTotal,@szmemo,@period,@usedtype,'T',-@InvoiceTotal , @InvoiceTag ,@Dtypeid,@Branchid,'T',@Billtype)
		if @@rowcount <=0 or @@Error <> 0 
		begin
			set @nRet = -9
			goto error
		end
		update dlya set redold='T' where vchcode=@nVchcode
		fetch next from CreateRed_cursor into @szatypeid, @szBtypeid, @dTotal, @szmemo, @period, @usedtype, @InvoiceTotal ,
			@InvoiceTag,@Branchid
	end 
	CLOSE CreateRed_cursor
	DEALLOCATE CreateRed_cursor
         -- 复制单据附件		 
    exec Xw_CopyAccessory @nVchcode,@nNewVchcode

	if @nVchType in (4,66) 
	begin
		delete from gatheringdly where gatheringvchcode=@nVchcode
--			if @@error<>0 goto error
	end
	set @RetTotalSaleMoney=isnull(@RetTotalSaleMoney,0)
	set @RetTotalJFJE=isnull(@RetTotalJFJE,0)

	DECLARE @otherRe int,@branchName varchar(100),@vchname varchar(100),@Reddraft int,@redOld varchar(10)
	IF @nVchType IN (222,232,234,224)
	BEGIN
			IF  EXISTS(select 1 FROM Branch where Checkandaccept =0 and branchid=@Redbranchid) or @procType = 'FZCS'
			BEGIN
				SELECT TOP 1 @message=number,@Reddraft=draft,@redOld=redold FROM Dlyndx where vchcode =@RedOtherVchCode
				
				IF @Reddraft <>2 OR @redOld='T' --还没有验收时\红冲过，不红冲
                Begin
                    IF  @CallSelf = 0 
                    commit tran RedAccount --因同时红冲配货及其验收单（222，232，224，234）而去掉游标,外移
					RETURN 0
                End
				EXEC @otherRe =FZZ_CreateRed  @RedOtherVchCode,@szptypeido output,@szbtypeido output,
					@szatypeido output,@szktypeido output,@szGeneralTotal output,@RetTotalSaleMoney output,
					@RetTotalJFJE output,@RetVipCardId output,@vipcardno output,@newvchcode output,
					@CurrentOperator,@message output,1
				IF @otherRe<0 	
				BEGIN
				    SET @nRet =@otherRe 
					goto error
				END
				SELECT TOP 1 @branchName =fullname from branch where  branchid=@Redbranchid
				IF @nVchType IN(222,224,232,234) 
				BEGIN
					UPDATE dlyndxb SET retypeid=@CurrentOperator,rdate=GETDATE() WHERE vchcode IN(@RedOtherVchCode,@nVchCode) 
					IF @@ERROR<>0 OR @@ROWCOUNT<0 GOTO ERROR
				END
				SET @vchname='验收单'
                IF @nVchType IN ( 232, 224 ) 
                    SET @vchname = '配货单'	
                IF @procType = 'FZCS' 
                    SET @message = '与之对应的单据编号为【' + @message + '】' + @vchname
                        + '也已红冲！'
                ELSE 
                    SET @message = '此单据收货机构【' + @branchName
                        + '】没有启用验收流程，与之对应的单据编号为【' + @message + '】' + @vchname
                        + '也已红冲！'
                IF @CallSelf = 0 
                    COMMIT TRAN RedAccount
                         --因同时红冲配货及其验收单（222，232，224，234）而去掉游标,外移
                RETURN 0
			END
			
	END
	
    IF  @CallSelf = 0 commit tran RedAccount --因同时红冲配货及其验收单（222，232，224，234）而去掉游标,外移
    
    --写备注信息
	--INSERT INTO dlyndxb(vchcode,metypeid,petypeid,mdate,pdate)
	-- VALUES (@nNewVchcode,'',@CurrentOperator,GETDATE(), GETDATE())
	IF EXISTS(SELECT 1 FROM dlyndxb WHERE vchcode=@nVchcode)
	BEGIN
		UPDATE dlyndxb SET retypeid=@CurrentOperator,rdate=GETDATE() WHERE Vchcode=	@nVchcode
		IF @@ERROR<>0 OR @@ROWCOUNT<0 GOTO ERROR
	END
	return 0
error:
	
	DECLARE @cur_state SMALLINT
	SET @cur_state = 0
	SELECT @cur_state = CURSOR_STATUS('global','cur')

    IF @cur_state= 1
    BEGIN
		CLOSE CreateRed_cursor
		DEALLOCATE CreateRed_cursor
	END
    IF @CallSelf = 0 
	rollback tran RedAccount
	set @szptypeido = @szptypeid
	set @szbtypeido = @szbtypeid
	set @szatypeido = @szatypeid
	set @szktypeido = @szktypeid
	if @nRetJ<0 set @nRet=@nRetJ
	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].[FZBS_FZCopyFromBak]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FZBS_FZCopyFromBak]
GO

create procedure FZBS_FZCopyFromBak
(@vchcode int,
 @number varchar(100),
 @Branchid varchar(50)
)
as
begin
  declare @newvchcode int
  declare @vipcardid int
  declare @vipcardno varchar(50)
  declare @vchtype int

  select @vipcardid = VipCardID,@vchtype = vchtype from dlyndx where vchcode = @vchcode 
  if @vipcardid <> 0
    select @vipcardno = cardno from vipcards where cardid = @vipcardid

  begin tran BeginAccount
  insert into dlyndx(BillType,VchType,Draft,Redold,Date,Number,BtypeId,BranchId,BranchId2,EtypeId,KtypeId,KtypeId2,IfCheck,Checke,Period,RedWord,Account,InputNo,Qty,Total,InvoiceTag,InvoiceTotal,Dtypeid,VipCardID,VipDiscount,BarterType,InputNO1,InputNO2,InputNO3,InputNO4,InputNO5,CheckAndAccept,IfOut,LimitTime,DlyVchcode,ZdDiscount,ZdDiscountprice,Preferential,AcceptState,AtypeId,AtypeTotal,ExpandId,BackMoney,IsExported,Flag,YSYFTotal,ForeignVchcode,AccountTime,SiteId,RetailBackFlag,CurrUnDoIntegral,LastUnDoIntegral,VerifyFlow,LJYSYFTotal,ForeVIPBalance,OrderList,Summary,SkipFlag,Comment,Xw_Vsf1,Xw_Vsf2,Xw_Vsf3,Xw_Vsf4,Xw_Vsf5,PHID,PrintNum,checkdate)
  select BillType,VchType,3 as Draft,Redold,Date,Number,BtypeId,BranchId,BranchId2,EtypeId,KtypeId,KtypeId2,IfCheck,Checke,Period,RedWord,Account,InputNo,Qty,Total,InvoiceTag,InvoiceTotal,Dtypeid,VipCardID,VipDiscount,BarterType,InputNO1,InputNO2,InputNO3,InputNO4,InputNO5,CheckAndAccept,IfOut,LimitTime,DlyVchcode,ZdDiscount,ZdDiscountprice,Preferential,AcceptState,AtypeId,AtypeTotal,ExpandId,BackMoney,IsExported,Flag,YSYFTotal,ForeignVchcode,AccountTime,SiteId,RetailBackFlag,CurrUnDoIntegral,LastUnDoIntegral,VerifyFlow,LJYSYFTotal,ForeVIPBalance,OrderList,Summary,SkipFlag,Comment,Xw_Vsf1,Xw_Vsf2,Xw_Vsf3,Xw_Vsf4,Xw_Vsf5,PHID,PrintNum,checkdate
  from dlyndx
  where vchcode = @vchcode
  if @@Rowcount<0 or @@error<>0   
  Begin  
    Rollback tran BeginAccount  
    return -20110223 
  end  
  set @newvchcode = @@identity
   declare	@qty  numeric(24,10)  
  declare	@total numeric(24,10)  

  select @qty = sum(qty) ,@total = sum(salemoney) from bakdly where vchcode = @vchcode
  update dlyndx set Expandid = 'LSJC',qty= @qty,total = @total where vchcode = @newvchcode
  if @@Rowcount<0 or @@error<>0   
  Begin  
    Rollback tran BeginAccount  
    return -20110223 
  end  
  insert into bakdly(BillType,Vchcode,VchType,BranchID,AtypeId,BtypeId,EtypeId,KtypeId,Dtypeid,PtypeId,CostMode,Qty,ColorId,Discount,VipCardID,VipDiscount,DiscountPrice,CostPrice,RetailPrice,TaxPrice,Price,CostTotal,Total,TaxTotal,Tax_Total,BargainTotal,DiscountTotal,Tax,Date,UsedType,Period,Unit,[Convert],JoinCostPrice,JoinCostTotal,MarketDiscount,MarketDiscount1,SaleMoney,PackCode,PackRate,PackQty,IfSupply,Comment,RowOrder,SaleMode,CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,OpID,PHRows)
  select BillType,@newvchcode,VchType,BranchID,AtypeId,BtypeId,EtypeId,KtypeId,Dtypeid,PtypeId,CostMode,Qty,ColorId,Discount,VipCardID,VipDiscount,DiscountPrice,CostPrice,RetailPrice,TaxPrice,Price,CostTotal,Total,TaxTotal,Tax_Total,BargainTotal,DiscountTotal,Tax,Date,UsedType,Period,Unit,[Convert],JoinCostPrice,JoinCostTotal,MarketDiscount,MarketDiscount1,SaleMoney,PackCode,PackRate,PackQty,IfSupply,Comment,RowOrder,SaleMode,CustValue1,CustValue2,CustValue3,CustValue4,CustValue5,CustValue6,OpID,PHRows
  from bakdly where vchcode = @vchcode
  if @@Rowcount<0 or @@error<>0   
  Begin  
    Rollback tran BeginAccount  
    return -20110223 
  end  
  --2013-11-25以下为老罗修改注释
--  insert into bakdlydetail(DlyOrder,SizeId,ColorID,Qty,CostTotal,Total,TaxTotal,Tax_Total,BargainTotal,[Convert],DiscountTotal,SaleMoney,JoinCostTotal,Usedtype,PHRows,Vchcode)  
--  select b.DlyOrder,a.SizeId,a.ColorID,a.Qty,a.CostTotal,a.Total,a.TaxTotal,a.Tax_Total,a.bargainTotal,a.[Convert],a.DiscountTotal,a.SaleMoney,a.JoinCostTotal,a.Usedtype,a.PHRows,@newvchcode
--  from bakdlydetail a,
--(select vchcode,dlyorder,ptypeid,colorid,TaxPrice,sign(qty) as signqty,Comment from bakdly where vchcode = @newvchcode) b,
--(select vchcode,dlyorder,ptypeid,colorid,TaxPrice,sign(qty) as signqty,Comment from bakdly where vchcode = @vchcode)c
--  where  a.dlyorder = c.dlyorder
--        and b.ptypeid = c.ptypeid
--        and b.colorid = c.colorid
--        and b.TaxPrice = c.TaxPrice ---加这个是因为有可能同一商品同一颜色不同价格是分两行的\
--        and b.signqty = c.signqty
--        AND b.comment=c.comment
--        and b.vchcode = @newvchcode
--2013-11-25以下为老罗修改增加
 insert into bakdlydetail(DlyOrder,SizeId,ColorID,Qty,CostTotal,Total,TaxTotal,Tax_Total,BargainTotal,[Convert],DiscountTotal,SaleMoney,JoinCostTotal,Usedtype,PHRows,Vchcode)
select b.DlyOrder,a.SizeId,a.ColorID,a.Qty,a.CostTotal,a.Total,a.TaxTotal,a.Tax_Total,a.bargainTotal,a.[Convert],a.DiscountTotal,a.SaleMoney,a.				JoinCostTotal,a.Usedtype,a.PHRows,@newvchcode
from bakdlydetail a INNER JOIN bakdly b ON a.phRows=b.phrows AND a.vchcode=@vchcode
WHERE b.vchcode=@newvchcode AND a.Usedtype=b.usedtype AND a.colorid=b.colorid        
   if @@Rowcount<0 or @@error<>0   
  Begin  
    Rollback tran BeginAccount  
    return -20110223 
  end 
  commit tran BeginAccount

 return @newvchcode
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/****** Object:  StoredProcedure [dbo].[CXGiftsAnalyse]    Script Date: 06/05/2012 16:20:41 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF exists (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CXGiftsAnalyse]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[CXGiftsAnalyse]
GO

--  ********************************************************************************************  
--  ||                                         
--  ||                                                 
--  ||   过程名称：CXGiftsAnalyse                                      
--  ||   过程功能：促销赠品分析  
--  ||
--  ||
--  ||==========================================================================================  
CREATE   PROCEDURE [dbo].[CXGiftsAnalyse]
(
  @dynTable as DynParameterTable readonly
  , @sqlCmd nvarchar(max) out --输出参数, 业务Sql片段
  , @decSql nvarchar(max) out --输出参数，参数声明Sql片段
  , @specSql nvarchar(max) out --输出参数，参数赋值Sql片段    
)
AS 
BEGIN

	DECLARE @SQLCmd1 VARCHAR(MAX)

	SET @SQLCmd1 = N''
	set @decSql = N'@dynParamTable as DynParameterTable readonly'
	set @specSql = N'@dynParamTable'

	SELECT @decSql += nchar(10) + nchar(9) + N', @' + ParaField + N' ' + DataType,
		   @specSql += nchar(10) + nchar(9) + isnull(N', ''' + ParaValue + N'''', ', null')
	from @dynTable
	WHERE datatype <> ''
	
	DECLARE @cols VARCHAR(3000),@group VARCHAR(500),@sort VARCHAR(500),@dlistfield VARCHAR(200),@leftPrice VARCHAR(2200), @ptypecategory VARCHAR(50),@ptypeid1 VARCHAR(10),@ptypeid2 VARCHAR(10),@ptypeid3 VARCHAR(10),@IsShowKtype INT
	SELECT  @dlistfield=','+paraValue+',' FROM @dynTable WHERE paraField = 'dlistfield'
	
	SELECT @ptypecategory=paraValue FROM @dynTable WHERE paraField = 'ptypecategory'
	IF @ptypecategory IS NULL
	BEGIN
		SET @ptypeid1 ='5'
	END
	ELSE
	BEGIN
		SET @ptypeid1 = CONVERT(VARCHAR(10),(SELECT a FROM Fn_splitWithOrderid(@ptypecategory,',') WHERE orderid = 1)*5)
		SET @ptypeid2 = CONVERT(VARCHAR(10),(SELECT a FROM Fn_splitWithOrderid(@ptypecategory,',') WHERE orderid = 2)*5)
		SET @ptypeid3 = CONVERT(VARCHAR(10),(SELECT a FROM Fn_splitWithOrderid(@ptypecategory,',') WHERE orderid = 3)*5)
	END
	
	SET @IsShowKtype=CHARINDEX('branchid',@dlistfield)
	SET @cols=@dlistfield
	SET @group=@dlistfield
	SET @sort=@dlistfield
	
	SET @cols=@cols+'Qty,Total,dhreftotal,costTotal,stockQty,'
	
	SET @cols=REPLACE(@cols,',ptypecategory,',',left(t.ptypeid,'+@ptypeid1+') ptypeid1,left(t.ptypeid,'+ISNULL(@ptypeid2,'0')+') ptypeid2,left(t.ptypeid,'+ISNULL(@ptypeid3,'0')+') ptypeid3,')
	SET @cols=REPLACE(@cols,',ptypeid,',',t.ptypeid,')
	SET @cols=REPLACE(@cols,',colorid,',',right(''''00000''''+cast (colorid as varchar),5) as ColorID,')
	SET @cols=REPLACE(@cols,',sizeid,',',right(''''00000''''+cast (SizeId as varchar),5) as SizeId,')
	
	SET @group=REPLACE(@group,',ptypecategory,',',left(t.ptypeid,'+@ptypeid1+'),left(t.ptypeid,'+ISNULL(@ptypeid2,'0')+'),left(t.ptypeid,'+ISNULL(@ptypeid3,'0')+'),')
	SET @group=REPLACE(@group,',ptypeid,',',t.ptypeid,')
	
	SET @sort=REPLACE(@sort,',branchid,',',DATA.BranchID,')
	SET @sort=REPLACE(@sort,',ptypecategory,',',DATA.ptypeid1,')
	SET @sort=REPLACE(@sort,',ptypeid,',',DATA.ptypeid,')
	SET @sort=REPLACE(@sort,',colorid,',',DATA.colorid,')
	SET @sort=REPLACE(@sort,',sizeid,',',DATA.SizeId,')
	
	--定义变量
	DECLARE @ctypeid nvarchar(60),@saletype nvarchar(60),@salepriceid nchar(60),@ptypeid nvarchar(60),@colorid nvarchar(60),@sizeid nvarchar(60),@assist1 INT,@assist2 INT,@assist3 INT,@assist4 INT,@assist5 INT,@assist6 INT,@assist7 INT,@assist8 INT
	SELECT  @salepriceid=paraValue FROM @dynTable WHERE paraField = 'salepriceid'
	SELECT  @ctypeid=paraValue FROM @dynTable WHERE paraField = 'ctypeid'
	SELECT  @saletype=paraValue FROM @dynTable WHERE paraField = 'saletype'
	SELECT  @ptypeid=paraValue FROM @dynTable WHERE paraField = 'ptypeid'
	SELECT  @colorid=paraValue FROM @dynTable WHERE paraField = 'colorid'
	SELECT  @sizeid=paraValue FROM @dynTable WHERE paraField = 'sizeid'
	SELECT  @assist1=paraValue FROM @dynTable WHERE paraField = 'assist1'
	SELECT  @assist2=paraValue FROM @dynTable WHERE paraField = 'assist2'
	SELECT  @assist3=paraValue FROM @dynTable WHERE paraField = 'assist3'
	SELECT  @assist4=paraValue FROM @dynTable WHERE paraField = 'assist4'
	SELECT  @assist5=paraValue FROM @dynTable WHERE paraField = 'assist5'
	SELECT  @assist6=paraValue FROM @dynTable WHERE paraField = 'assist6'
	SELECT  @assist7=paraValue FROM @dynTable WHERE paraField = 'assist7'
	SELECT  @assist8=paraValue FROM @dynTable WHERE paraField = 'assist8'
	
	--替换显示字段
	SET @cols=REPLACE(@cols,',Qty,',',SUM(qty) as qty,')
	--SET @cols=REPLACE(@cols,',Total,',',ROUND(SUM(l.qty*l.RetailPrice),@dig_total) Total,')
	SET @cols=REPLACE(@cols,',Total,',',ROUND(SUM(Total),@dig_total) Total,')
	--SET @cols=REPLACE(@cols,',costTotal,',',ROUND(SUM(g.price*l.qty),@dig_total) costTotal,')
	SET @cols=REPLACE(@cols,',costTotal,',',ROUND(SUM(costTotal),@dig_total) costTotal,')
	--SET @cols=REPLACE(@cols,',stockQty,',',MAX(g.qty) stockqty,')
	SET @cols=REPLACE(@cols,',stockQty,',',SUM(stockqty) stockqty,')
	
	IF @salepriceid IS NULL OR @salepriceid=''
	BEGIN
		SET @cols=REPLACE(@cols,',dhreftotal,',',ROUND(SUM(Total),@dig_total) AS dhreftotal,')
		SET @leftPrice=''
	END
	ELSE
	BEGIN
		SET @cols=REPLACE(@cols,',dhreftotal,',',ROUND(SUM(CONVERT(DECIMAL(24,10),pp.Price)*CONVERT(DECIMAL(24,10),Qty)),@dig_total) AS dhreftotal,')
		SET @leftPrice='LEFT JOIN dbo.PtypePrice AS pp ON pp.PtypeId=t.PTypeId AND pp.PriceTypeId=@salepriceid'
	END	
	
	IF CHARINDEX(',assist1,',@cols)>0 OR @assist1 IS NOT NULL
	BEGIN
		SET @leftPrice=@leftPrice+' LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist1,gg.AttributeID 
			FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh 
				ON hh.AttributeId = gg.AttributeID AND TypeID = 1) A1 
			ON A1.PtypeId = t.PtypeId '+CASE WHEN @assist1 IS NULL THEN '' ELSE ' AND A1.AttributeID = @assist1' END
	END	
	IF CHARINDEX(',assist2,',@cols)>0 OR @assist2 IS NOT NULL
	BEGIN
		SET @leftPrice=@leftPrice+' LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist2,gg.AttributeID 
			FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh 
				ON hh.AttributeId = gg.AttributeID AND TypeID = 2) A2 
			ON A2.PtypeId = t.PtypeId '+CASE WHEN @assist2 IS NULL THEN '' ELSE ' AND A2.AttributeID = @assist2' END
	END	
	IF CHARINDEX(',assist3,',@cols)>0 OR @assist3 IS NOT NULL
	BEGIN
		SET @leftPrice=@leftPrice+' LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist3,gg.AttributeID 
			FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh 
				ON hh.AttributeId = gg.AttributeID AND TypeID = 3) A3 
			ON A3.PtypeId = t.PtypeId '+CASE WHEN @assist3 IS NULL THEN '' ELSE ' AND A3.AttributeID = @assist3' END
	END	
	IF CHARINDEX(',assist4,',@cols)>0 OR @assist4 IS NOT NULL
	BEGIN
		SET @leftPrice=@leftPrice+' LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist4,gg.AttributeID 
			FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh 
				ON hh.AttributeId = gg.AttributeID AND TypeID = 4) A4 
			ON A4.PtypeId = t.PtypeId '+CASE WHEN @assist4 IS NULL THEN '' ELSE ' AND A4.AttributeID = @assist4' END
	END	
	IF CHARINDEX(',assist5,',@cols)>0 OR @assist5 IS NOT NULL
	BEGIN
		SET @leftPrice=@leftPrice+' LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist5,gg.AttributeID 
			FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh 
				ON hh.AttributeId = gg.AttributeID AND TypeID = 5) A5 
			ON A5.PtypeId = t.PtypeId '+CASE WHEN @assist5 IS NULL THEN '' ELSE ' AND A5.AttributeID = @assist5' END
	END	
	IF CHARINDEX(',assist6,',@cols)>0 OR @assist6 IS NOT NULL
	BEGIN
		SET @leftPrice=@leftPrice+' LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist6,gg.AttributeID 
			FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh 
				ON hh.AttributeId = gg.AttributeID AND TypeID = 6) A6 
			ON A6.PtypeId = t.PtypeId '+CASE WHEN @assist6 IS NULL THEN '' ELSE ' AND A6.AttributeID = @assist6' END
	END	
	IF CHARINDEX(',assist7,',@cols)>0 OR @assist7 IS NOT NULL
	BEGIN
		SET @leftPrice=@leftPrice+' LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist7,gg.AttributeID 
			FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh 
				ON hh.AttributeId = gg.AttributeID AND TypeID = 7) A7 
			ON A7.PtypeId = t.PtypeId '+CASE WHEN @assist7 IS NULL THEN '' ELSE ' AND A7.AttributeID = @assist7' END
	END	
	IF CHARINDEX(',assist8,',@cols)>0 OR @assist8 IS NOT NULL
	BEGIN
		SET @leftPrice=@leftPrice+' LEFT JOIN (SELECT hh.PtypeId,gg.UserName AS assist8,gg.AttributeID 
			FROM dbo.AssistAttribute gg INNER JOIN PtypeAttribute hh 
				ON hh.AttributeId = gg.AttributeID AND TypeID = 8) A8 
			ON A8.PtypeId = t.PtypeId '+CASE WHEN @assist8 IS NULL THEN '' ELSE ' AND A8.AttributeID = @assist8' END
	END	
	
	IF LEN(@cols)>1 SET @cols=LEFT(RIGHT(@cols,LEN(@cols)-1),LEN(@cols)-2)
	IF LEN(@group)>1 SET @group=LEFT(RIGHT(@group,LEN(@group)-1),LEN(@group)-2)
	IF LEN(@sort)>1 SET @sort=LEFT(RIGHT(@sort,LEN(@sort)-1),LEN(@sort)-2)
	
	
	SET @SQLCmd1 =' 
	
		IF object_id(''''tempdb..#tempstock'''') is not null   
                drop table #tempstock 
                
        DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
		EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output 

		SELECT __cols__
			INTO #tmpsort
		FROM (
			SELECT '+CASE WHEN @IsShowKtype>0 THEN 'd.BranchID,' ELSE '' END +'d.ptypeid,d.colorid,d.SizeId,d.qty,d.Total,ROUND((CONVERT(DECIMAL(24,10),g.price)*CONVERT(DECIMAL(24,10),d.qty)),@dig_total) costTotal,g.qty stockqty
			FROM 
				(SELECT '+CASE WHEN @IsShowKtype>0 THEN 'i.Jtypeid as branchid,' ELSE '' END +'l.ptypeid,l.colorid,l.SizeId,SUM(l.qty) qty,
						ROUND(SUM(l.total),@dig_total) Total
					FROM tpx_SaleIndex i 
						INNER JOIN tpx_SaleList l on i.keyid=l.zbkeyid
						INNER JOIN tpx_CXBillIndex v 
							on '''',''''+l.CXBillID LIKE ''''%,''''+CONVERT(VARCHAR(10),v.billNumberId)+'''',%''''
					WHERE v.billtype=2 
						AND i.[saledate] BETWEEN @billdate_s AND @billdate_e
						AND EXISTS(SELECT 1 FROM (
								SELECT * FROM FN_GetPowerRangePList(@oprid,'''''''') 
							) FilterP WHERE l.ptypeid = FilterP.typeid)
						AND EXISTS(SELECT 1 FROM FN_GetStockListOfBranch(@oprid,'''''''','''''''') FilterK 
							WHERE i.ktypeId = Filterk.KtypeId)
						'+CASE WHEN @saletype=-1 THEN '' ELSE ' AND v.saletype=@saletype' END +
						CASE WHEN @ctypeid is null THEN '' ELSE ' AND i.Jtypeid IN(SELECT b.branchid
							FROM branch b INNER JOIN dbo.Fn_split(@ctypeid,'''','''') n ON b.branchid like n.a+''''%'''')' END + 
						CASE WHEN @ptypeid is null THEN '' ELSE ' AND l.ptypeid LIKE @ptypeid ' END +
						CASE WHEN @colorid is null THEN '' ELSE ' AND l.colorID = @colorid ' END +
						CASE WHEN @sizeid is null THEN '' ELSE ' AND l.sizeid = @sizeid ' END +
						CASE WHEN @assist1 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = l.PtypeId AND pa.AttributeID = @assist1) ' END +
						CASE WHEN @assist2 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = l.PtypeId AND pa.AttributeID = @assist2) ' END +
						CASE WHEN @assist3 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = l.PtypeId AND pa.AttributeID = @assist3) ' END +
						CASE WHEN @assist4 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = l.PtypeId AND pa.AttributeID = @assist4) ' END +
						CASE WHEN @assist5 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = l.PtypeId AND pa.AttributeID = @assist5) ' END +
						CASE WHEN @assist6 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = l.PtypeId AND pa.AttributeID = @assist6) ' END +
						CASE WHEN @assist7 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = l.PtypeId AND pa.AttributeID = @assist7) ' END +
						CASE WHEN @assist8 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = l.PtypeId AND pa.AttributeID = @assist8) ' END +'
					GROUP BY '+CASE WHEN @IsShowKtype>0 THEN 'i.Jtypeid,' ELSE '' END +'l.ptypeid,l.colorid,l.SizeId
				) d
				LEFT JOIN (
					SELECT ptypeid,'+CASE WHEN @IsShowKtype>0 THEN 'k.Branchid,' ELSE '' END +'colorid,sizeid,SUM(gsd.qty) qty,ISNULL(CONVERT(DECIMAL(24,10),SUM(gsd.Total))/NULLIF(CONVERT(DECIMAL(24,10),SUM(gsd.qty)),0),MAX(gs.price)) price 
					FROM goodsstocks gs INNER JOIN Goodsstockdetail gsd ON gs.Orderid=gsd.Orderid 
					'+CASE WHEN @IsShowKtype>0 THEN ' INNER JOIN stock k ON gs.ktypeid=k.typeid' ELSE '' END+'
					WHERE EXISTS(SELECT 1 FROM (
								SELECT * FROM FN_GetPowerRangePList(@oprid,'''''''') 
							) FilterP WHERE gs.ptypeid = FilterP.typeid)
						AND EXISTS(SELECT 1 FROM FN_GetStockListOfBranch(@oprid,'''''''','''''''') FilterK 
							WHERE gs.ktypeId = Filterk.KtypeId)
						'+CASE WHEN @ctypeid is null THEN '' ELSE ' AND gs.ktypeid IN(SELECT k.TypeId
							FROM branch b INNER JOIN dbo.Fn_split(@ctypeid,'''','''') n ON b.branchid like n.a+''''%''''
								INNER JOIN stock k ON b.branchid=k.branchid)' END + 
						CASE WHEN @ptypeid is null THEN '' ELSE ' AND gs.ptypeid LIKE @ptypeid ' END +
						CASE WHEN @colorid is null THEN '' ELSE ' AND gsd.colorID = @colorid ' END +
						CASE WHEN @sizeid is null THEN '' ELSE ' AND gsd.sizeid = @sizeid ' END +
						CASE WHEN @assist1 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = gs.PtypeId AND pa.AttributeID = @assist1) ' END +
						CASE WHEN @assist2 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = gs.PtypeId AND pa.AttributeID = @assist2) ' END +
						CASE WHEN @assist3 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = gs.PtypeId AND pa.AttributeID = @assist3) ' END +
						CASE WHEN @assist4 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = gs.PtypeId AND pa.AttributeID = @assist4) ' END +
						CASE WHEN @assist5 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = gs.PtypeId AND pa.AttributeID = @assist5) ' END +
						CASE WHEN @assist6 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = gs.PtypeId AND pa.AttributeID = @assist6) ' END +
						CASE WHEN @assist7 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = gs.PtypeId AND pa.AttributeID = @assist7) ' END +
						CASE WHEN @assist8 IS NULL THEN '' ELSE ' AND EXISTS (SELECT 1 FROM dbo.PtypeAttribute pa 
							WHERE pa.PtypeId = gs.PtypeId AND pa.AttributeID = @assist8) ' END +'
					GROUP BY ptypeid,'+CASE WHEN @IsShowKtype>0 THEN 'k.Branchid,' ELSE '' END +'colorid,sizeid
					) g on d.ptypeid=g.ptypeid AND g.colorid=d.colorid AND g.sizeid=d.sizeid '+CASE WHEN @IsShowKtype>0 THEN ' AND g.Branchid=d.Branchid' ELSE '' END +'
			) t
			__lefttable__
		GROUP BY __group__;

				
	/*最终结果表*/
with Data AS (
SELECT * FROM #tmpsort
),
	'
	
	SET @SQLCmd1=REPLACE(@SQLCmd1,'__cols__',@cols)
	SET @SQLCmd1=REPLACE(@SQLCmd1,'__group__',@group)
	SET @SQLCmd1=REPLACE(@SQLCmd1,'__lefttable__',@leftPrice)
	
	
-- 排序信息
declare @sortInfo varchar(255) = isnull((select ParaValue from @dynTable where ParaField = '__SortInfo__') + ',', '')
-- 排序联接信息
declare @sortJoinInfo varchar(555) = isnull((select replace(ParaValue, '__LeftTable__', 'Data') from @dynTable where ParaField = '__SortJoinInfo__'), '')

	set @sqlCmd = cast(
	(
		@SQLCmd1
		+ '
		__ReportData__ AS (
		select dense_rank() over (order by '+@sortInfo+@sort+' desc) __RowNo__,DATA.*
		from Data ' + @sortJoinInfo + ')'
	) as nvarchar(max))
END




/******************************************20140214********************************************/
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





CREATE   procedure FN_FZGetMakeCardInfo    
(    
 @BeginDate varchar(10),    
 @EndDate varchar(10),    
 @MinCardNo varchar(18),    
 @MaxCardNo varchar(18),    
 @Typeid varchar(15),    
 @State varchar(15),    
 @BranchId varchar(50)    --发卡机构
)    
as    
begin    
   declare @SQL varchar(8000)    
    set @sql = 'select right(''0000000000'' + cast(a.Cardid as varchar),10) as VcTypeId,a.cardno,a.a.holdername,b.name as TypeName,right(''00000'' + cast(b.OrderId as varchar),5) as Typeid,     
              case when a.cardstate = 0 then ''停用'' else ''使用'' end as cardstate,  
              a.makeDate,a.ValidDate,c.displayName as DiscountName,
	      d.fullname as BranchName,d.BranchId ,makecomment	      
              from vipcards a     
              left join vipcardtypes b on a.CardTypeID = b.orderid    
              left join pricetype c on b.pricetypeid = c.pricetypeid    
              left join Branch d on a.handoutdept = d.BranchId                	      
              where a.deleted = 0 and a.makeDate >=''' + @BeginDate  + ''' and a.makeDate <=''' + @EndDate +''''    
    if @MinCardNo <> ''     
       set @sql = @sql + ' and a.cardno >= ''' + @MinCardNo + ''''    
    if @MaxCardNo <> ''     
       set @sql = @sql + ' and a.cardno <= ''' + @MaxCardNo + ''''    
    if @Typeid <> ''     
       set @sql = @sql + ' and b.orderid =' + @typeid    
    if @State <> ''     
       set @sql = @sql + ' and a.cardstate =' + @state    
    if @BranchId <> ''    
       set @sql = @sql + ' and d.BranchId = ''' + @BranchId + ''''    
--print @sql  
   exec(@sql)    
--  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].[FN_FZGetVipIntegralModifyHis]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FN_FZGetVipIntegralModifyHis]
GO




CREATE  procedure FN_FZGetVipIntegralModifyHis  
(  
 @BeginDate  	varchar(10),  
 @EndDate 	varchar(10),  
 @CardNo 	varchar(18),  
 @HolderName 	varchar(66),  
 @Etypeid 	varchar(50)  ,
 @branchid 	varchar(50) =''	--发卡机构 。总部为空，加盟商发卡是加盟商机构ID	  
)  
as  
begin  

DECLARE @SQL VARCHAR(8000)

SET @SQL='  Select right(''0000000000'' + cast(a.cardid as varchar),10) as VCTypeid ,b.cardno,b.holdername, a.[date],IntegralTotal - Integral as OldIntegral,
  Integral as AddIntegral,IntegralTotal as NewIntegral  
  from VipIntegralDetail a  
  left join Vipcards b on a.cardid = b.cardid  '
IF @CardNo <> ''
SELECT @sql = @sql + ' Where a.[date] >='''+@BeginDate+''' and a.[Date] <='''+@EndDate+''' and b.cardno = '''+@cardno+''' and b.HolderName like ''%'+@HolderName+'%'' and a.Etypeid like '''+@Etypeid+'%''  and  '
ELSE 
SELECT @sql = @sql + ' Where a.[date] >='''+@BeginDate+''' and a.[Date] <='''+@EndDate+''' and b.cardno like ''%'+@cardno+'%'' and b.HolderName like ''%'+@HolderName+'%'' and a.Etypeid like '''+@Etypeid+'%''  and  '
IF NOT EXISTS(SELECT * FROM sysdata WHERE subname = 'ProcTypeName' AND SubValue = 'FZCS')
begin
if	@branchid='' 
   	SET	@SQL=@SQL+'  b.cardTypeID in (SELECT OrderID FROM VipCardTypes WHERE CreatBranchID LIKE ''00001%'') and vchcode = 0 and BatchNo <> -1 and b.deleted = 0  and IntegralConsume = 0 and consumetotal = 0   '
   else
	SET	@SQL=@SQL+'  b.cardTypeID in (SELECT OrderID FROM VipCardTypes WHERE CreatBranchID ='''+@branchid+''') and vchcode = 0 and BatchNo <> -1 and b.deleted = 0  and IntegralConsume = 0 and consumetotal = 0   '

END
ELSE 
BEGIN
if	@branchid='' 
   	SET	@SQL=@SQL+'  vchcode = 0 and BatchNo <> -1 and b.deleted = 0  and IntegralConsume = 0 and consumetotal = 0   '
   else
	SET	@SQL=@SQL+'  HandOutDept = '''+ @branchid +''' and vchcode = 0 and BatchNo <> -1 and b.deleted = 0  and IntegralConsume = 0 and consumetotal = 0  and HandOutDept in (select branchid from VipCardbound where VipCardbound.CardTypeId = b.CardTypeId)'
	
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 OFF 
GO

IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'[dbo].[FZGetBillCourse]')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
    DROP PROCEDURE [dbo].[FZGetBillCourse]
GO




--万能查询
--  **************************************************************************************************************************************
--  ||                                                                                        
--  ||   FZGetBillCourse                                     
--  ||   过程功能：单据经营历程
--  ||=========================================================================================
--  ||=========================================================================================   
--  ||   返回值：         值                                     说明
--  ||       ----------------------------------------------------------------------------------------
--  ||                    0                                 执行成功
--  ||                  －1                               执行失败
--  ||==========================================================================================
CREATE  PROCEDURE FZGetBillCourse
    (
      @BillCenterType INT,
      @vchtype INT,
      @begindate VARCHAR(10),
      @enddate VARCHAR(10),
      @BranchId VARCHAR(50),
      @Ktypeid VARCHAR(50),
      @Btypeid VARCHAR(50),
      @BillState INT,
      @Ptypeid VARCHAR(50),
      @Etypeid VARCHAR(50),
      @InputNo VARCHAR(50),
      @Atypeid VARCHAR(50),
      @number VARCHAR(50),
      @summary VARCHAR(256),
      @Comment VARCHAR(256),
      @CustField VARCHAR(100),
      @InputNo2 VARCHAR(50),
      @InputNo3 VARCHAR(50),
      @InputNo4 VARCHAR(50),
      @InputNo5 VARCHAR(50),
      @CurrOperatorID VARCHAR(50),--当前操作员ID
      @PHID VARCHAR(1)='0'
    )
AS 
    SET NOCOUNT ON
  
    DECLARE @Sql VARCHAR(8000)
    --测试让去掉负数 when a.vchtype in(115,129,130) then -a.Total
    SET @Sql = 'select distinct a.vchcode,a.vchtype,v.name as vchname,a.vchcode,a.draft,a.date,a.number,a.InputNo,account,a.redword,a.AcceptState,a.checkandaccept,
              a.ktypeid,isnull(k2.fullname,'''') as KType2Name,a.etypeid,a.redold,right(''0000000000''+cast(a.vipcardid as varchar),10) as vctypeid,
              isnull(vc.cardno,'''') as cardno,isnull(vc.holdername,'''') as holdername,
			  a.qty,CASE WHEN a.vchtype in (212,218,222,234) THEN a.BranchId2 ELSE a.BranchId END as BcTypeId,a.BtypeId,a.summary,a.comment,
              			case when a.vchtype=170 then 0
				     when a.vchtype=125 then 0
				else a.Total 
			  end as Total,a.PrintNum,AccountTime,e.fullname as inputname , e1.fullname as inputname1,'
	
	IF @BillCenterType IN (0,1)
    BEGIN
		SET @Sql = @Sql + ' '''' AS inputname2,'''' AS inputname3,'''' AS inputname4,'''' AS inputname5, '
    END
    ELSE
    BEGIN
		SET @Sql = @Sql + ' e2.fullname as inputname2,e3.fullname as inputname3,e4.fullname as inputname4,e5.fullname as inputname5, '
    END
    			  
	SET @Sql = @Sql + 'a.vipcardid,a.ifcheck,'
	
	IF @BillCenterType = 1
	BEGIN
		SET @Sql = @Sql + ' '''' AS auditFlag '
	END
	ELSE
	BEGIN
		SET @Sql = @Sql + '	CASE (SELECT IfAudit FROM AuditingBill AB WHERE exists(select 1 from AuditingFlowSet AF where AB.AuditingID=AF.AuditingID ) AND AB.VchCode=a.vchcode AND BillIndexType= ''1'') 
			WHEN 0 THEN ''待审核''
			WHEN 1 THEN ''审核通过''
			WHEN -1 THEN ''审核未通过''
			ELSE ''原始单据''
			END AS auditFlag '			  	
	END
	IF @BillCenterType=1 --经营历程，显示过账人
	BEGIN
		SET @Sql = @Sql + ',a2.petypeid'
	END
	SET @Sql = @Sql + ' from dlyndx a '
          
    IF @PtypeId <> ''
        OR @CustField <> ''
        OR @Comment <> ''
        OR @Atypeid <> '' 
        BEGIN
            IF @BillCenterType = 0 
                SET @Sql = @Sql
                    + ' inner join bakdly b on a.vchcode=b.vchcode '
            ELSE 
                IF @BillCenterType IN ( 4, 2, 3 ) 
                    SET @Sql = @Sql
                        + ' inner join (Select AtypeId,vchcode,ptypeid,comment,custvalue1,custvalue2,custvalue3,custvalue4,custvalue5,custvalue6 from dlydata
					     union all
					     Select AtypeId,vchcode,ptypeid,comment,custvalue1,custvalue2,custvalue3,custvalue4,custvalue5,custvalue6 from bakdly) b on a.vchcode=b.vchcode '
                ELSE 
                    SET @Sql = @Sql
                        + ' inner join (select '''' as atypeid,ptypeid,comment,vchcode,custvalue1,custvalue2,custvalue3,custvalue4,custvalue5,custvalue6 from dlydata
					     union all
					     Select atypeid,'''' as ptypeid,'''' as comment,vchcode,'' '' custvalue1, '' '' custvalue2, '' '' custvalue3,'' '' custvalue4,'' '' custvalue5,'' '' custvalue6
						from dlya)  b on a.vchcode=b.vchcode '


            IF @PtypeId <> '' 
                SET @Sql = @Sql + ' and b.ptypeid like ' + '''' + @Ptypeid
                    + '%'''
            IF @CustField <> '' 
                SET @Sql = @Sql + ' and (b.custvalue1 like ' + '''%'
                    + @CustField + '%''' + 'or b.custvalue2 like ' + '''%'
                    + @CustField + '%''' + 'or b.custvalue3 like ' + '''%'
                    + @CustField + '%''' + 'or b.custvalue4 like ' + '''%'
                    + @CustField + '%''' + 'or b.custvalue5 like ' + '''%'
                    + @CustField + '%''' + 'or b.custvalue6 like ' + '''%'
                    + @CustField + '%'')' 
            IF @Comment <> '' 
                SET @Sql = @Sql + ' and a.comment like ' + '''%' + @Comment
                    + '%'''     
            IF @Atypeid <> '' 
                SET @Sql = @Sql + ' and a.atypeid like ' + '''' + @Atypeid
                    + '%'''      
        END
     
    SET @Sql = @Sql + ' left join vipcards vc on a.vipcardid=vc.CardID  '  
    SET @Sql = @Sql + ' left join vchtype v on a.vchtype=v.vchtype  ' 
    SET @Sql = @Sql + ' left join Stock k2 on a.KTypeId2=k2.TypeId  ' 
    SET @Sql = @Sql + ' left join employee e on a.inputno=e.TypeId  ' 
    SET @Sql = @Sql + ' left join employee e1 on a.inputno1=e1.TypeId  ' 
    
    IF (@BillCenterType <> 0 AND @BillCenterType <> 1)    
    BEGIN
		SET @Sql = @Sql + ' left join employee e2 on a.inputno2=e2.TypeId  ' 
		SET @Sql = @Sql + ' left join employee e3 on a.inputno3=e3.TypeId  ' 
		SET @Sql = @Sql + ' left join employee e4 on a.inputno4=e4.TypeId  ' 
		SET @Sql = @Sql + ' left join employee e5 on a.inputno5=e5.TypeId  ' 
    END
    IF @BillCenterType=1 --经营历程，显示过账人
    BEGIN
		SET @Sql = @Sql + ' left join dlyndxb a2 on a.vchcode=a2.vchcode  ' 
    END


    SET @Sql = @Sql + ' where 1=1 '
--    SET @Sql = @Sql
--       + ' and (branchid2<>'+''''+') or (a.branchid not in (SELECT BranchId FROM dbo.Branch WHERE SelfHelp = 1 AND branchid <> '''+@BranchId+''''+') and branchid2='+''''''+')'--过滤独立机构的数据
    IF @vchtype <> 0 
        SET @Sql = @Sql + ' and a.vchtype=' + CAST(@vchtype AS VARCHAR(10))
    IF @begindate <>'' AND @enddate <>''
	SET @Sql = @sql + ' and a.date BETWEEN '+ '''' + @begindate + ''' AND '+ '''' + @enddate + ''''
    ELSE IF @begindate <> '' 
        SET @Sql = @Sql + ' and a.date >= ' + '''' + @begindate + ''''
    ELSE IF @enddate <> '' 
        SET @Sql = @Sql + ' and a.date <= ' + '''' + @enddate + ''''
    IF @BranchId <> '' 
        SET @Sql = @Sql + ' and (a.BranchId like ' + '''' + @BranchId + '%'
            + '''' + ' or BranchId2 like ' + '''' + @BranchId + '%' + ''''
            + ') '
    IF @KtypeId <> '' 
        SET @Sql = @Sql + ' and (a.KtypeId like ' + '''' + @KtypeId + '%'
            + '''' + ' or KtypeId2 like ' + '''' + @KtypeId + '%' + ''''
            + ') '
    IF @BtypeId <> '' 
        SET @Sql = @Sql + ' and a.BtypeId like ' + '''' + @BtypeId + '%'''
    IF @EtypeId <> '' 
        SET @Sql = @Sql + ' and a.EtypeId like ' + '''' + @EtypeId + '%'''
    IF @InputNo <> '' 
        SET @Sql = @Sql + ' and a.InputNo like ' + '''' + @InputNo + '%'''
    IF @number <> '' 
        SET @Sql = @Sql + ' and a.number like ' + '''%' + @number + '%'''
    IF @summary <> '' 
        SET @Sql = @Sql + ' and a.summary like ' + '''%' + @summary + '%'''
    IF @InputNo2 <> '' 
        BEGIN
            IF @BillCenterType = 3 
                SET @Sql = @Sql + ' and (a.InputNo2 like ' + '''' + @InputNo2
                    + '%'' or a.InputNo3  like  ' + +'''' + @InputNo2 + '%'')'
            ELSE 
                SET @Sql = @Sql + ' and a.InputNo2 like ' + '''' + @InputNo2
                    + '%'''
        END
    IF @InputNo3 <> '' 
        SET @Sql = @Sql + ' and a.InputNo3 like ' + '''' + @InputNo3 + '%'''
    IF @InputNo4 <> '' 
        SET @Sql = @Sql + ' and a.InputNo4 like ' + '''' + @InputNo4 + '%'''
    IF @InputNo5 <> '' 
        SET @Sql = @Sql + ' and a.InputNo5 like ' + '''' + @InputNo5 + '%'''
    IF @PHID <>'0' 
		SET @Sql = @Sql + ' and a.PHID = CASE WHEN (a.vchtype = 212 OR a.vchtype = 218) THEN ' + @PHID + ' ELSE a.PHID END '
        
    --根据选择的机构过滤配货相关单据及其验收单据
    IF @BranchId <> '' 
        BEGIN
            IF LEFT(@BranchId, 5) = '00004' 
                BEGIN
                    SET @Sql = @Sql
                        + ' and a.vchtype <> 222 and a.vchtype <> 224 '
                END
            ELSE 
                BEGIN
                    SET @Sql = @Sql
                        + ' and a.vchtype <> 232 and a.vchtype <> 234 '
                END
        END


  --@BillCenterType 0=业务草稿 1=经营历程 2=单据审核 3=配送单验收, 4=调配验收
    IF @BillCenterType = 0 
        BEGIN	
            SET @Sql = @Sql + ' and a.draft in(1,10) and a.vchtype<>230 '
            --在业务草稿查询中过滤验收单
            SET @Sql = @Sql + ' and a.vchtype <> 224 and a.vchtype <> 232 '
            --如果操作员有没查看他人草稿的权限，则将单据过滤掉，防止通过业务草稿的其他功能按钮变相查看他人草稿
            IF @CurrOperatorID<>'00000' AND NOT EXISTS(SELECT 1 FROM dbo.EmployeePower WHERE EtypeId = @CurrOperatorID AND ModuleId = '0901' AND ActionId = '145')
				SET @Sql = @Sql + ' AND (a.InputNo = '''+@CurrOperatorID+''') '
        END 
    IF @BillCenterType = 1       -- 经营历程
        BEGIN	
            SET @Sql = @Sql + ' and a.draft=2'
            IF @BillState = 0 
                SET @Sql = @Sql + ''				 			--0：所有类型
            IF @BillState = 1 
                SET @Sql = @Sql + ' and a.redold<>' + '''T'''	--1：不包括红单
            IF @BillState = 2 
                SET @Sql = @Sql + ' and a.redold =' + '''T'''	--2：只包括红单
        END	
    IF @BillCenterType = 2        -- 审核
        BEGIN	
            SET @Sql = @Sql + ' and a.draft=5'
            IF @BillState = 0 
                SET @Sql = @Sql + ''                   		--0：所有单据
            IF @BillState = 1 
                SET @Sql = @Sql + ' and a.acceptState=''0000'''	--1：未审核
            IF @BillState = 2 
                SET @Sql = @Sql + ' and a.acceptState<>''0000'''--2：已审核
            IF @BillState = 3 
                SET @Sql = @Sql + ' and a.ifcheck=1'		--3：审核完成
        END	
    IF @BillCenterType = 3     -- 配送单验收
        BEGIN	
            SET @Sql = @Sql + ' and a.vchtype in (212,215,218,230)'
            IF @BillState = 0 
                SET @Sql = @Sql
                    + ' and (a.draft in (4,2) or (a.vchtype=230 and a.draft=1)) '   --0：所有单据
            IF @BillState = 1 
                SET @Sql = @Sql
                    + ' and a.draft =4 or (a.vchtype=230 and a.draft=1)'			--1：未验收
            IF @BillState = 2 
                SET @Sql = @Sql
                    + ' and a.draft =2 and a.CheckAndAccept<>2 and redold=''F'''			--2：已验收
            IF @BillState = 3 
                SET @Sql = @Sql
                    + ' and a.draft in (4,2) and a.CheckAndAccept=2'	--1：已拒收
            IF @BillState = 4 
                SET @Sql = @Sql
                    + ' and (a.draft in (4,2) or (a.vchtype=230 and a.draft=1)) and a.redold<>'
                    + '''T'''	--4：不包括红单
        END	
    IF @BillCenterType = 4    -- 调配单验收
        BEGIN	
            SET @Sql = @Sql + ' and a.vchtype in (170)'
            IF @BillState = 0 
                SET @Sql = @Sql + ' and a.draft in(9,2)'   					    --0：所有单据
            IF @BillState = 1 
                SET @Sql = @Sql + ' and a.draft=9'			--1：未验收
            IF @BillState = 2 
                SET @Sql = @Sql + ' and a.draft=2'			--2：已验收
	--  if @BillState=3   	set @Sql=@Sql+' and a.draft=2'	--3：已过帐
            IF @BillState = 3 
                SET @Sql = @Sql + ' and a.draft in(9,2) and a.redold<>'
                    + '''T'''	--4：不包括红单
        END
        
    --添加多级权限范围过滤(具有某类基本信息所有权限时不过滤)
    IF NOT EXISTS(SELECT 1 FROM dbo.UserPowerRange WHERE  TypeID = '00000' AND EtypeID = @CurrOperatorID AND BaseType = 1)
    SET @Sql = @Sql
        + ' AND (exists(SELECT 1 FROM FN_GetPowerRangeEList('''+@CurrOperatorID+''','''') where a.etypeid=typeid) or isnull(a.etypeid,'''') = '''')'
    IF NOT EXISTS(SELECT 1 FROM dbo.UserPowerRange WHERE  TypeID = '00000' AND EtypeID = @CurrOperatorID AND BaseType = 5)
    SET @Sql = @Sql
        + ' AND (exists(SELECT 1 FROM FN_GetPowerRangeBCList('''+@CurrOperatorID+''','''') where a.branchid=branchid or a.branchid2=branchid) or isnull(a.branchid,'''')='''')'
    IF NOT EXISTS(SELECT 1 FROM dbo.UserPowerRange WHERE  TypeID = '00000' AND EtypeID = @CurrOperatorID AND BaseType = 4)
    SET @Sql = @Sql
        + ' AND (exists(SELECT 1 FROM FN_GetPowerRangeBList('''+@CurrOperatorID+''','''', ''1,2,3,4,6,7'') where a.btypeid=typeid) OR ISNULL(a.btypeid,'''') = '''' OR a.VchType IN (212,218))'
    
    --由于对双仓库和单仓库的单据，仓库权限判断规则不一致，所以用UNION ALL连接两个结果集------------------------------------------------------------------
    DECLARE @Sql_1 VARCHAR(8000)
    DECLARE @Sql_2 VARCHAR(8000)    
    IF NOT EXISTS(SELECT 1 FROM dbo.UserPowerRange WHERE  TypeID = '00000' AND EtypeID = @CurrOperatorID AND BaseType = 6)
    SET @Sql_1 = @Sql
        + ' AND (exists(SELECT 1 FROM FN_GetStockListOfBranchIni('''+@CurrOperatorID+''','''','''') where a.KtypeId=KtypeId) or a.KtypeId = '''')'
        + ' AND (exists(SELECT 1 FROM FN_GetStockListOfBranchIni('''+@CurrOperatorID+''','''','''') where a.KtypeId2=KtypeId) or a.KtypeId2 = '''')'
        + ' AND a.VchType NOT IN (16,17,21,24,212,218,222,224,232,234) '    
    IF NOT EXISTS(SELECT 1 FROM dbo.UserPowerRange WHERE  TypeID = '00000' AND EtypeID = @CurrOperatorID AND BaseType = 6)
    SET @Sql_2 = @Sql
        + ' AND ((exists(SELECT 1 FROM FN_GetStockListOfBranchIni('''+@CurrOperatorID+''','''','''') where a.KtypeId=KtypeId) or a.KtypeId = '''')'
        + ' OR (exists(SELECT 1 FROM FN_GetStockListOfBranchIni('''+@CurrOperatorID+''','''','''') where a.KtypeId2=KtypeId) or a.KtypeId2 = ''''))'
        + ' AND a.VchType IN (16,17,21,24,212,218,222,224,232,234) '    
    IF NOT EXISTS(SELECT 1 FROM dbo.UserPowerRange WHERE  TypeID = '00000' AND EtypeID = @CurrOperatorID AND BaseType = 6)
    SET @Sql = @Sql_1 + ' UNION ALL ' + @Sql_2
    -----------------------------------------------------------------------------------------------------------------------------------------------------
    
    --排序    
    SET @Sql = @Sql + ' ORDER BY accounttime'
    
    PRINT @Sql
    EXEC (@Sql)
    
    IF @@rowcount = 0 
        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_PosCashStat_NEW]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GP_PosCashStat_NEW]
GO

 
  
--  ********************************************************************************************  
--  ||                                                                                          
--  ||   过程名称：F_AccountYearCfg                                       
--  ||   过程功能：Pos收银流水查询  
--  ||   modify by 老罗 2012-11-09  
--  ||==========================================================================================  
CREATE PROCEDURE GP_PosCashStat_NEW  
    (  
      @SaleDateBegin VARCHAR(10),  
      @SaleDateEnd VARCHAR(10),  
      @SaleTimeBegin VARCHAR(8),  
      @SaleTimeEnd VARCHAR(8),  
      @BillCode VARCHAR(200),  
      @PosName VARCHAR(30),  
      @ktypeid VARCHAR(50),  
      @CashierETypeID VARCHAR(50),  
      @SalesManETypeID VARCHAR(50),  
      @VipNo VARCHAR(18),  
      @Draft VARCHAR(8), --传的值: -1(全部),0(POS小票),1(草稿),2(过账)     
      @BranchID VARCHAR(50),  
      @OperatorID VARCHAR(50)  
    )  
AS  
  
 DECLARE   @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int   
 EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output   
  
    DECLARE @DateTimeBegin VARCHAR(30),  
        @DateTimeEnd VARCHAR(30),  
        @sql VARCHAR(4000)      
    SET @DateTimeBegin = @SaleDateBegin + ' ' + @SaleTimeBegin      
    SET @DateTimeEnd = @SaleDateEnd + ' ' + @SaleTimeEnd     
      
 IF object_id('tempdb..#Emp') is not null     
 drop table #Emp  
 SELECT typeid,FullName INTO #Emp   FROM dbo.FN_GetPowerRangeEList(@OperatorID,'')  
  
   
 IF object_id('tempdb..#keyEmp') is not null     
 drop table #keyEmp  
 SELECT tbl.keyId,tbl.Salesman,tbl.Salesmanid  
 INTO #keyEmp  
 FROM  
 (  
  SELECT DISTINCT si.keyId,ee.FullName AS Salesman,ee.TypeId AS Salesmanid  
  FROM dbo.tpx_SaleIndex si  
  INNER JOIN dbo.tpx_SaleList sl ON si.keyId = sl.ZBKeyId  
  INNER JOIN dbo.tpx_SaleManList sml ON sml.CBKeyId = sl.keyid  
  INNER JOIN #Emp ee ON ee.TypeId = sml.ETypeId  
  WHERE si.SaleTime BETWEEN @DateTimeBegin AND @DateTimeEnd  
 ) tbl  
   
 --删除未包含在营业员筛选条件中的数据  
 DELETE FROM #keyEmp WHERE keyId NOT IN   
 (  
  SELECT DISTINCT keyId FROM #keyEmp  
  WHERE Salesmanid LIKE @SalesManETypeID + '%'  
 )  
   
 IF object_id('tempdb..#keyEmp1') is not null     
 drop table #keyEmp1  
 SELECT tbl1.keyId,tbl1.Salesman  
 INTO #keyEmp1  
 FROM(  
 SELECT ke.keyId,Salesman = STUFF((SELECT ',' + kee.Salesman FROM #keyEmp kee WHERE kee.keyId = ke.keyid ORDER BY kee.keyId FOR XML PATH('')),1,1,'')  
 FROM #keyEmp ke GROUP BY ke.keyId) tbl1  
  
 IF object_id('tempdb..#ktype') is not null     
 drop table #ktype  
 SELECT KtypeId INTO #ktype FROM FN_GetStockListOfBranch(@OperatorID,@BranchID,@ktypeid)  

IF object_id('tempdb..#saleindex') is not null     
drop table #saleindex  
SELECT keyId,SaleTime,PosVchCode,
    BillCode,Total,BillDiscount,
    RetReplaCashSum,Cashier,PosID,
    KtypeID,Draft,DraftVchcode,VipCardID,
    FinallyTotal,JTypeId
INTO #saleindex
FROM dbo.tpx_SaleIndex C
WHERE EXISTS(SELECT 1 FROM #ktype br WHERE br.KtypeId = C.ktypeid OR C.ktypeid = '')  
AND C.VtypeId = '00001'  --仅统计零售单据  
AND C.SaleTime BETWEEN @DateTimeBegin AND @DateTimeEnd  
AND C.Cashier LIKE @CashierETypeID+'%'  
AND C.BillCode LIKE '%' + @BillCode + '%'  
AND EXISTS(SELECT 1 FROM #Emp ep WHERE ep.typeid = c.Cashier)  
AND EXISTS(SELECT 1 FROM #keyEmp kep WHERE kep.keyid = C.keyid)  

 IF object_id('tempdb..##CommonPosSaleIndextemp') is not null     
 drop table #CommonPosSaleIndextemp  
    CREATE TABLE #CommonPosSaleIndextemp  
        (  
          POSVchCode INT,  
          BillCode VARCHAR(200),  
          SaleDate DATETIME,  
          Total numeric(24,10),  
          BillDisCount numeric(24,10),  
          RetReplaceCashSum numeric(24,10),  
          Cashier VARCHAR(100),  
          Salesman VARCHAR(100),  
          PosID VARCHAR(100),  
          ktypeid VARCHAR(50),  
          Draft INT,  
          DraftVchcode INT,  
          VipCardID INT,  
          SaleType VARCHAR(40),  
          GatheringMoney numeric(24,10),    
          GatheringVipID VARCHAR(50),  
          yhtotal numeric(24,10)  
        )    
          
 /*      
 把原来的4个收款的列，改成行，让用户看见 SELECT * FROM CommonPosSaleIndex      
 */  
   
 INSERT INTO #CommonPosSaleIndextemp  
    SELECT  C.PosVchCode,  
            C.BillCode,  
            C.SaleTime AS 'SaleDate',  
            C.Total,  
            CASE WHEN C.Total<0 THEN -C.BillDisCount ELSE C.BillDisCount END AS BillDisCount,  
            C.RetReplaCashSum AS RetReplaceCashSum,  
            C.Cashier,  
            --C.Salesman,  
            (SELECT kep.Salesman FROM #keyEmp1 kep WHERE kep.keyId = C.keyId) AS Salesman,  
            C.PosID,  
            C.ktypeid,  
            C.Draft,  
            C.DraftVchcode,  
            C.VipCardID,  
            SaleType,  
            GatheringMoney,  
            GatheringVipID,  
            yhtab.yhtotal1 - C.FinallyTotal AS yhtotal  
    FROM    #saleindex C  
            INNER JOIN (
                SELECT I.keyId,  
                (SELECT pcc.AtypeName FROM tpx_PosCashTypeConfig pcc WHERE pcc.Keyid = L.Akeyid AND pcc.Jtypeid = I.jtypeid) AS SaleType,  
				SUM(ISNULL(L.[Total],0)) GatheringMoney,  
				'' GatheringVipID  
				FROM #saleindex I LEFT JOIN tpx_SalePayList L  ON L.ZBKeyId=I.keyId  
				WHERE ISNULL(L.AKeyId,'') <> '00004'
				GROUP BY AKeyId,I.keyId,[VIPId],JTypeId   
            ) #tab ON C.keyId = #tab.keyId  
            INNER JOIN 
			(
			    SELECT ROUND(SUM(CONVERT(NUMERIC(24,10),tpx_sl.Qty)* CONVERT(NUMERIC(24,10),tpx_sl.RetailPrice)),@dig_total) AS yhtotal1,
				tpx_sl.zbkeyid  
                FROM dbo.tpx_SaleList tpx_sl  
                GROUP BY tpx_sl.ZBKeyId  
            ) yhtab ON yhtab.zbkeyid = C.keyId  
      
    INSERT INTO #CommonPosSaleIndextemp  
    SELECT C.PosVchCode,  
            C.BillCode,  
            C.SaleTime AS 'SaleDate',  
            C.Total,  
            CASE WHEN C.Total<0 THEN -C.BillDisCount ELSE C.BillDisCount END AS BillDisCount,  
            C.RetReplaCashSum AS RetReplaceCashSum,  
            C.Cashier,  
            --C.Salesman,  
            (SELECT kep.Salesman FROM #keyEmp1 kep WHERE kep.keyId = C.keyId) AS Salesman,  
            C.PosID,  
            C.ktypeid,  
            C.Draft,  
            C.DraftVchcode,  
            C.VipCardID,  
            SaleType,  
            CASE WHEN  C.Total < 0 THEN  -GatheringMoney ELSE GatheringMoney END GatheringMoney,  
            GatheringVipID,  
            yhtab.yhtotal1 - C.FinallyTotal AS yhtotal  
    FROM    #saleindex C  
            INNER JOIN (SELECT I.keyId,  
            (SELECT pcc.AtypeName FROM tpx_PosCashTypeConfig pcc WHERE pcc.Keyid = tsml.Akeyid AND pcc.Jtypeid = I.jtypeid) AS SaleType,  
            SUM(ISNULL(L.[Total],0)) GatheringMoney,  
            L.[VIPId] GatheringVipID  
                                 FROM #saleindex I LEFT JOIN dbo.tpx_SaleVipList L ON L.ZBKeyId=I.keyId  
                                 INNER JOIN dbo.tpx_SalePayList tsml ON I.keyId = tsml.ZBKeyId  
                                 WHERE tsml.AKeyId = '00004'
                                 GROUP BY I.keyId,L.[VIPId],JTypeId,tsml.AKeyId   
                       ) #tab ON C.keyId = #tab.keyId  
            INNER JOIN (SELECT ROUND(SUM(CONVERT(NUMERIC(24,10),tpx_sl.Qty)* CONVERT(NUMERIC(24,10),tpx_sl.RetailPrice)),@dig_total) AS yhtotal1,tpx_sl.zbkeyid  
            FROM dbo.tpx_SaleList tpx_sl
            GROUP BY tpx_sl.ZBKeyId  
            ) yhtab ON yhtab.zbkeyid = C.keyId  
  
       SET @sql = '
        IF object_id(''tempdb..##NewTable'') is not null     
           drop table ##NewTable  
       SELECT a.PosVchCode,a.BillCode,SaleDate,        
         a.Total,BillDisCount,RetReplaceCashSum,SaleType,GatheringMoney,GatheringVipID,        
         Cashier,Salesman,a.yhtotal,  
         --(select ISNULL(vc.CardNo,'''') from VipCards vc where vc.CardID = vipcardid) as VipCardID,   
		 --right(''0000000000''+cast(vipcardid as varchar),10) as VipCardID,
         ISNULL(v1.cardno,'''') as VipCardID,
         ISNULL(a.ktypeid,'''') AS sFullname,       
         ISNULL(po.Fullname,'''') AS posFullname,--V.CardNo AS cardno,--  
         ISNULL(V.CardNo,'''') AS CardNo,
		 --right(''0000000000''+cast(GatheringVipID as varchar),10) as CardNo,
         a.draft,a.DraftVchcode                   
         INTO ##NewTable            
  FROM #CommonPosSaleIndextemp a            
       --LEFT JOIN stock st   ON a.ktypeid=st.typeid  and st.deleted=0                    
       LEFT JOIN tpx_PosInfo   po   ON a.PosID=po.PosID             
       LEFT JOIN VipCards V ON a.GatheringVipID=V.CardID  
       LEFT JOIN VipCards V1 ON a.VipCardID=V1.CardID  
  WHERE BillCode like ''%' + @BillCode + '%''            
        AND ISNULL(po.Fullname,'''') like ''%' + @PosName + '%'''  
      
    SET @sql = @sql + ' Order by a.PosVchCode'      
       
    EXEC (@sql)      
      
    SELECT  PosVchCode,  
            BillCode,  
            SaleDate,  
            Total,  
            BillDisCount,  
            RetReplaceCashSum,  
            SaleType,  
            GatheringMoney,  
            GatheringVipID,  
            Cashier,  
            Salesman,  
            sFullname,  
            posFullname,  
            CardNo,  
            draft,  
            DraftVchcode,  
            yhtotal,  
            VipCardID  
    INTO    #PosUserReturnTable  
    FROM    ( SELECT    PosVchCode,  
                        BillCode,  
                        SaleDate,  
                        Total,  
                        BillDisCount,  
                        RetReplaceCashSum,  
                        SaleType,  
                        GatheringMoney,  
                        GatheringVipID,  
                        E.fullname AS Cashier,  
                        Salesman,  
                        sFullname,  
                        posFullname,  
                        CardNo,  
                        N.draft,  
                        n.DraftVchcode,  
                        yhtotal,  
                        VipCardID  
              FROM      ##NewTable N  
                        LEFT JOIN Employee E ON N.Cashier = E.typeid  
                                                AND E.deleted = 0  
            ) A  
    ORDER BY PosVchCode    
    
    SELECT  IDENTITY( NUMERIC(9),1,1 ) AS NoID,  
            BillCode,  
            SaleDate,  
            Total,  
            BillDisCount,  
            RetReplaceCashSum,  
            SaleType,  
            GatheringMoney,  
            GatheringVipID,  
            Cashier,  
            Salesman,  
            sFullname,  
            posFullname,  
            CardNo,  
            draft,  
            DraftVchcode,  
            posvchcode,  
            yhtotal,  
            VipCardID  
    INTO    #PosUserReturnTable2  
    FROM    #PosUserReturnTable  
    WHERE   PosVchCode IN ( SELECT  PosVchCode  
                            FROM    #PosUserReturnTable  
                            WHERE   CardNo LIKE '%' + @VipNo + '%' )  --只要储值卡查询有一条，该张收银的信息全部都要显示    
    ORDER BY PosVchCode,SaleDate    
    
    DROP TABLE ##NewTable  
    DROP TABLE #CommonPosSaleIndextemp  
    --DROP TABLE ##CommonPosSaleIndex      
    DROP TABLE #PosUserReturnTable      
        
    CREATE TABLE #PosUserReturnTable1  
        (  
          NoID NUMERIC(9),  
          BillCode VARCHAR(200),  
          SaleDate DATETIME,  
          Total numeric(24,10),  
          BillDisCount numeric(24,10),  
          RetReplaceCashSum numeric(24,10),  
          SaleType VARCHAR(40),  
          GatheringMoney numeric(24,10),    
 --SaveAccountCardNo varchar(100),    
          Cashier VARCHAR(100),  
          Salesman VARCHAR(100),  
          sFullname VARCHAR(100),  
          posFullname VARCHAR(100),  
          CardNo VARCHAR(100),  
          draft INT,  
          DraftVchcode INT,  
          posvchcode NUMERIC(18, 0),  
          yhtotal NUMERIC(24, 10),  
          VipCardID VARCHAR(1000)  
        )    
    
/*    
直接在储存过程中处理，如果Pos小票中，BillCode和销售时间一起有相同的，就以第一条记录显示完整，其他的只保留 收款方式(SaleType)  收款金额(GatheringMoney)  收款卡号(SaveAccountCardNo)     
*/    
    DECLARE @OLDBillCode VARCHAR(200)    
    DECLARE @NewNoID NUMERIC(9)    
    DECLARE @OLDSaleDate DATETIME   --以前只判断 BillCode 相同，就能确定单据是否是同一张，（由于不同单据的BillCode经常重复，现在在加上销售时间进行区别 ）    
    
    DECLARE @NoID1 NUMERIC(9),  
        @BillCode1 VARCHAR(200),  
        @SaleDate1 DATETIME,  
        @Total1 numeric(24,10),  
        @BillDisCount1 numeric(24,10),  
        @RetReplaceCashSum1 numeric(24,10),  
        @SaleType1 VARCHAR(40),  
        @GatheringMoney1 numeric(24,10),    
 --@SaveAccountCardNo1 varchar(100),    
        @Cashier1 VARCHAR(100),  
        @Salesman1 VARCHAR(100),  
        @sFullname1 VARCHAR(100),  
        @posFullname1 VARCHAR(100),  
        @CardNo1 VARCHAR(100),  
        @draftflag INT,  
        @DraftVchcodeflag INT,  
        @posvchcode NUMERIC(18, 0),    
  @yhtotal1 numeric(24,10),  
  @VipCardID varchar(1000)  
  
  
  INSERT  INTO #PosUserReturnTable1  
  
  select			
	NoID,  
	BillCode,  
	SaleDate,  
	Total,  
	BillDisCount,  
	RetReplaceCashSum,  
	SaleType,  
	GatheringMoney,  
	Cashier,  
	Salesman,  
	sFullname,  
	posFullname,  
	CardNo,  
	draft,  
	DraftVchcode,  
	posvchcode,  
	yhtotal,  
	VipCardID
	FROM (
					  SELECT			
						NoID,  
						BillCode,  
						SaleDate,  
						Total,  
						BillDisCount,  
						RetReplaceCashSum,  
						SaleType,  
						GatheringMoney,  
						Cashier,  
						Salesman,  
						sFullname,  
						posFullname,  
						CardNo,  
						draft,  
						DraftVchcode,  
						posvchcode,  
						yhtotal,  
						VipCardID,
						ROW_NUMBER() OVER(PARTITION BY saledate,BillCode ORDER BY saledate,BillCode) AS 'RowNumber'
						FROM    #PosUserReturnTable2     
				)      x      where RowNumber=1
     
  INSERT  INTO #PosUserReturnTable1                                    
select			
	noid,  
  '',  
  NULL,  
  NULL,  
  NULL,  
  NULL,  
  SaleType,  
  GatheringMoney,  
  '',  
'',  
  '',  
  '',  
  CardNo,  
  1,  
  DraftVchcode,  
  posvchcode,  
  NULL,  
  NULL  
	FROM (
					  SELECT			
						NoID,  
						BillCode,  
						SaleDate,  
						Total,  
						BillDisCount,  
						RetReplaceCashSum,  
						SaleType,  
						GatheringMoney,  
						Cashier,  
						Salesman,  
						sFullname,  
						posFullname,  
						CardNo,  
						draft,  
						DraftVchcode,  
						posvchcode,  
						yhtotal,  
						VipCardID,
						ROW_NUMBER() OVER(PARTITION BY saledate,BillCode ORDER BY saledate,BillCode) AS 'RowNumber'
						FROM    #PosUserReturnTable2     
				)      x      where RowNumber<>1				
				
			
  
  
    IF @Draft = '-1'   
        BEGIN  
            SELECT  noid,  
                    BillCode,  
                    CONVERT(VARCHAR(20),SaleDate,20) SaleDate,  
                    a.Total,  
                    BillDisCount,  
                    RetReplaceCashSum,  
                    SaleType,  
                    GatheringMoney,  
                    Cashier,  
                    Salesman,  
                    sFullname,  
                    posFullname,  
                    CardNo,  
                    --CASE draft WHEN 0 THEN 'POS小票' WHEN 1 THEN '草稿' WHEN 2 THEN '过账' ELSE '' END AS draft, --传的值: -1(全部),0(POS小票),1(草稿),2(过账),  
                    CASE billcode WHEN '' THEN '' ELSE  
                    CASE ISNULL(CAST(a.draft AS VARCHAR), 'X')  
                      + ISNULL(CAST(b.Draft AS VARCHAR), 'X')  
                      WHEN '0X' THEN 'POS小票'  
                      WHEN 'XX' THEN 'POS小票'  
                      WHEN '12' THEN '过账'  
                      WHEN '22' THEN '过账'  
                      WHEN 'X2' THEN '过账'  
                      ELSE '草稿'  
                    END   
                    END AS draft,  
                    b.Draft AS dlyndxdraft,  
                    DraftVchcode,  
                    posvchcode,  
                    yhtotal,  
                    a.VipCardID  
            FROM    #PosUserReturnTable1 a  
                    LEFT JOIN dbo.DlyNdx b ON a.DraftVchcode = b.Vchcode     
                    order by noid
        END     
      
    ELSE   
        BEGIN  
            IF @Draft = '0'   
                SET @Draft = 'POS小票'  
            IF @Draft = '1'   
                SET @Draft = '草稿'  
            IF @Draft = '2'                   SET @Draft = '过账'  
  
            SELECT  noid,  
                    BillCode,  
                    CONVERT(VARCHAR(20),SaleDate,20) SaleDate,  
                    a.Total,  
                    BillDisCount,  
                    RetReplaceCashSum,  
                    SaleType,  
                    GatheringMoney,  
                    Cashier,  
                    Salesman,  
                    sFullname,  
                    posFullname,  
                    CardNo,  
                    --CASE draft WHEN 0 THEN 'POS小票' WHEN 1 THEN '草稿' WHEN 2 THEN '过账' ELSE '' END AS draft, --传的值: -1(全部),0(POS小票),1(草稿),2(过账),  
                    CASE billcode WHEN '' THEN '' ELSE  
                    CASE ISNULL(CAST(a.draft AS VARCHAR), 'X')  
                      + ISNULL(CAST(b.Draft AS VARCHAR), 'X')  
                      WHEN '0X' THEN 'POS小票'  
                      WHEN 'XX' THEN 'POS小票'  
                      WHEN '12' THEN '过账'  
                      WHEN '22' THEN '过账'  
                      WHEN 'X2' THEN '过账'  
                      ELSE '草稿'  
                    END   
                    END AS draft,  
                    b.Draft AS dlyndxdraft,  
                    DraftVchcode,  
                    posvchcode,  
                    yhtotal,  
                    a.VipCardID  
            FROM    #PosUserReturnTable1 a  
                    LEFT JOIN dbo.DlyNdx b ON a.DraftVchcode = b.Vchcode  
            WHERE   CASE ISNULL(CAST(a.draft AS VARCHAR), 'X')  
                      + ISNULL(CAST(b.Draft AS VARCHAR), 'X')  
                      WHEN '0X' THEN 'POS小票'  
                      WHEN 'XX' THEN 'POS小票'  
                      WHEN '12' THEN '过账'  
                      WHEN '22' THEN '过账'  
                      WHEN 'X2' THEN '过账'  
                      ELSE '草稿'  
                    END = @Draft  
                     order by noid
        END  
        --PRINT @draft  
          
    DROP TABLE #PosUserReturnTable1    
    DROP TABLE #PosUserReturnTable2    
    DROP TABLE #keyEmp  
    DROP TABLE #keyEmp1  
    
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS 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_BillGetPrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FN_BillGetPrice]
GO

/*----------修改记录-----------*/
--文有明 2012-07-19 修改读取价格跟踪的配置
/*-----------END---------------*/

CREATE  PROCEDURE FN_BillGetPrice
(	
	@VchType		int,
	@PtypeId		varchar(50),
	@KtypeId		varchar(50),
	@BtypeId		varchar(50), 
    @VipId			int,
	@ColorId          	int,
	@Price		  	numeric(24,10)    	output,		--单价
	@Discount	  	numeric(24,10)    	output,		--折扣
	@DiscountPrice		numeric(24,10)    	output,		--折后单价
	@RetailPrice      	numeric(24,10)    	output,		--零售价
	@CostPrice        	numeric(24,10)    	output,		--成本价
	@VipDiscount      	numeric(24,10)    	output,		--Vip折扣
	@MarketDiscount   	numeric(24,10)    	output,		--商场扣率
	@Tax              	numeric(24,10)=0  	output,		--商场专柜专用（税率）
	@ErrMsg			varchar(800)		output,		--返回错误信息
	@OperatorId		varchar(50),				--当前操作员Id,用以获得价格类型权限范围
	@IsPrintMessage		int = 0,
	@KtypeId2		varchar(50)='',
	@BtypeId2		varchar(50)=''
)
AS

	----做加盟商退货单取价格跟踪的信息，要用到最近配货价格
	IF (@VchType in(234,223) AND @KtypeId2<>'' AND @BtypeId2<>'')
	BEGIN
		SET @KtypeId = @KtypeId2
		SET @BtypeId = @BtypeId2
	END
	
	--根据当前仓库，取得当前主体机构Ｉｄ
	Declare @BranchId 		varchar(50)
	Select @BranchId = Branchid From Stock Where TypeId = @KtypeId
	If @@ROWCOUNT=0
	Begin
		Set @ErrMsg = '仓库不存在，不能取得所属机构'
		GoTo Err		
	End

	If @IsPrintMessage=1 print '基础价格:'
	--取得当前商品零售价
	Select @RetailPrice = IsNull(Price,0) From PtypePrice pp Where pp.PtypeId=@PtypeId And pp.PriceTypeId = 'LSSJ1'
	If @RetailPrice Is Null Set @RetailPrice = 0
	If @IsPrintMessage=1 print '商品零售价:'+Cast(@RetailPrice as varchar(30))

	--取得当前商品成本价
	Declare   @Record     BIT --判断记录是否存在
	Declare   @IniOver    BIT --判断是否为期初
	Set @Record=0
	--Select 	@IniOver =SubValue From sysdata Where SubName='iniover'
	select @IniOver = iniover from branch where BranchId=@BranchId
	If @VchType=70	--盘点单
	Begin
		Select Top 1 @CostPrice=price From dbo.GoodsstockBackup Where KtypeId=@KtypeId and PtypeId=@PtypeId
	End
	Else
	Begin
		Declare @CostMode int
		Select @CostMode=CostMode From ptype where Typeid=@PtypeId
		If @IniOver=1
		Begin
			If Exists(Select 1 From GoodsStocks Where PtypeId=@PtypeId And KtypeId=@KtypeId) Set @Record=1
			If @CostMode <>3
			Begin
				If IsNull(@ColorId,0)<>0 
				Begin
					Select Top 1 @CostPrice=(Total/qty) From GoodsStocks 
					Where PtypeId=@PtypeId And KtypeId=@KtypeId And qty<>0
						And orderid in (Select g.orderid From GoodsstockDetail gg,Goodsstocks g 
								Where g.ptypeid=@PtypeId and g.ptypeid=@PtypeId And g.KtypeId=@KtypeId and g.KtypeId=@KtypeId And gg.orderid=g.orderid And gg.colorid=@ColorId)
					Order By orderid Asc
				End
				Else
				Begin
					Select Top 1 @CostPrice =(Total/qty) From GoodsStocks  
					Where PtypeId=@PtypeId And KtypeId=@KtypeId And qty <>0
					Order By orderid Asc
				End
			End
			Else
			Begin
			 	Select top 1 @CostPrice =(Total/qty) From GoodsStocks
					Where PtypeId=@PtypeId And KtypeId=@KtypeId and qty<>0 
				Order By orderid Asc
			End
		End
		Else
		Begin
			If Exists(Select 1 From dbo.IniGoodsStocks Where PtypeId=@PtypeId And KtypeId=@KtypeId) Set @record=1
			if @CostMode <>3
			Begin 
				If IsNull(@colorid,0)<>0 
				Begin
					Select Top 1 @CostPrice =(Total/qty) From iniGoodsStocks  
					Where PtypeId=@PtypeId And KtypeId=@KtypeId And qty<>0
						And orderid In (Select g.orderid From iniGoodsDetail gg,iniGoodsStocks g 
								where ptypeid=@PtypeId And KtypeId=@KtypeId And gg.orderid=g.orderid And gg.colorid=@colorid)
					Order By orderid Asc
				End
				Else
				Begin
					Select Top 1 @Costprice=(Total/qty) From iniGoodsStocks
						Where ptypeid=@PtypeId And ktypeid=@KtypeId And qty<>0
					Order By orderid Asc
				End
			End
			Else
			Begin
				Select  @Costprice=(Total/qty) From iniGoodsStocks
				Where ptypeid=@PtypeId And ktypeid=@KtypeId and qty<>0 
				Order By orderid Asc
			End
		END
		If @Vchtype not in (251,252,16,57) and (@CostPrice is Null Or @CostPrice=0) And @record=0
			Select @CostPrice=recprice From Ptype Where typeid=@PtypeId
		Select @CostPrice=isnull(@CostPrice,0)
	End
	If @IsPrintMessage=1    print '成本价：'+Cast(@CostPrice as varchar(30))	
	

	--取得机构零售价、零售折扣、配货价、配货折扣
	Declare @BranchRetailPrice	numeric(24,10)		--机构零售价
	Declare @BranchRetailDiscount	numeric(24,10)		--机构零售折扣
	Declare @BranchRationPrice	numeric(24,10)		--机构配货价
	Declare @BranchRationDiscount	numeric(24,10)		--机构配货折扣
	Select @BranchRetailPrice=IsNull(Price,0) From PtypePrice pp,BtypeDistribute bd, FN_GetPowerRangePriceTypeList(@OperatorId) pt 
	Where bd.Type=0 And bd.BranchId=@BranchId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.PriceTypeId And pp.PriceTypeId=pt.PriceTypeId
	Select @BranchRetailDiscount=IsNull(Price,0) From PtypePrice pp,BtypeDistribute bd, FN_GetPowerRangePriceTypeList(@OperatorId) pt  
	Where bd.Type=0 And bd.BranchId=@BranchId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.DiscountTypeId And pp.PriceTypeId=pt.PriceTypeId

	
	If @VchType = 234 	--配货退货单取加盟商本身配货价
	Begin
		Select @BranchRationPrice=IsNull(Price,0) From PtypePrice pp,BtypeDistribute bd ,FN_GetPowerRangePriceTypeList(@OperatorId) pt 
		Where bd.Type=4 And bd.BranchId=@BranchId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.PriceTypeId And pp.PriceTypeId=pt.PriceTypeId
		Select @BranchRationDiscount=IsNull(Price,0) From PtypePrice pp,BtypeDistribute bd ,FN_GetPowerRangePriceTypeList(@OperatorId) pt 
		Where bd.Type=4 And bd.BranchId=@BranchId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.DiscountTypeId And pp.PriceTypeId=pt.PriceTypeId
	End
	Else
	Begin
		--配货价和配货折扣取收货机构所设的配货价和折扣
		Select @BranchRationPrice=IsNull(Price,0) From PtypePrice pp,BtypeDistribute bd ,FN_GetPowerRangePriceTypeList(@OperatorId) pt 
		Where bd.Type=4 And bd.BranchId=@BtypeId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.PriceTypeId And pp.PriceTypeId=pt.PriceTypeId
		Select @BranchRationDiscount=IsNull(Price,0) From PtypePrice pp,BtypeDistribute bd ,FN_GetPowerRangePriceTypeList(@OperatorId) pt 
		Where bd.Type=4 And bd.BranchId=@BtypeId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.DiscountTypeId And pp.PriceTypeId=pt.PriceTypeId
	End
	If @BranchRetailPrice Is Null    Set @BranchRetailPrice = 0
	If @BranchRetailDiscount Is Null    Set @BranchRetailDiscount = 0
	If @BranchRationPrice Is Null    Set @BranchRationPrice = 0
	If @BranchRationDiscount Is Null    Set @BranchRationDiscount = 0
	If @IsPrintMessage=1
	Begin
		print '机构零售价:'+Cast(@BranchRetailPrice as varchar(30))
		print '机构零售折扣:'+Cast(@BranchRetailDiscount as varchar(30))
		print '机构配货价:'+Cast(@BranchRationPrice as varchar(30))
		print '机构配货折扣:'+Cast(@BranchRationDiscount as varchar(30))
	End

	--取得是否使作VIP，及VIP会员价
	Declare @IfVip			int			--1：使用Vip，0：不使用
	Declare @VipCardType	     	int  			--0：会员价卡，1：折扣卡
	Declare @VipPriceTypeId 	varchar(20)		--Vip会员价或折扣的价格类型ＩＤ
	Declare @VipPrice 		numeric(24,10)		--会员价
	Declare @VipDisCountMode int ---- 1:是折上折 0:是最低折 2:是VIP折扣
	Set @IfVip=0
	Set @VipPrice=0
	Set @VipDiscount=100
	Set @VipDisCountMode=-1
	--判断VIP卡及适用范围是否有效
	If Exists(Select * from VIPCards v,VipCardBound b where v.CardID=@VipId And b.BranchId=@BranchId And v.CardTypeId = b.CardTypeId)
   	Begin
		Set @IfVip = 1

		Select @VipCardType=t.Type,@VipPriceTypeId=PriceTypeId ,@VipDisCountMode=DisCountMode
		From VipCards v, VipCardTypes t Where v.CardId=@VipId And v.CardTypeId=t.OrderId
	 	If @VipCardType = 1
		Begin
			--折扣卡，取VIP折扣
			--销售出库单、销售换货单、销售退货单、零售单、代销零售单不需要价格权限限制
			IF @VchType=11 or @VchType=24 or @VchType=45 or @VchType=12 or @VchType=100
			Select @VipDiscount=IsNull(pp.Price,0) From PtypePrice pp Where pp.PtypeId=@PtypeId And pp.PriceTypeId=@VipPriceTypeId
			ELSE
			Select @VipDiscount=IsNull(pp.Price,0) From PtypePrice pp, FN_GetPowerRangePriceTypeList(@OperatorId) pt Where pp.PtypeId=@PtypeId And pp.PriceTypeId=@VipPriceTypeId And pt.PriceTypeId = pp.PriceTypeId
		End
		Else
		Begin
			--会员价卡，取VIP会员价
			--销售出库单、销售换货单、销售退货单、零售单、代销零售单不需要价格权限限制
			IF @VchType=11 or @VchType=24 or @VchType=45 or @VchType=12 or @VchType=100
			Select @VipPrice=IsNull(pp.Price,0) From PtypePrice pp Where pp.PtypeId=@PtypeId And pp.PriceTypeId=@VipPriceTypeId
			ELSE
			Select @VipPrice=IsNull(pp.Price,0) From PtypePrice pp, FN_GetPowerRangePriceTypeList(@OperatorId) pt Where pp.PtypeId=@PtypeId And pp.PriceTypeId=@VipPriceTypeId And pt.PriceTypeId = pp.PriceTypeId
		End
		If @VipPrice Is Null    Set @VipPrice=0
		If @VipDiscount Is Null    Set @VipDiscount=100
	End
	If @IsPrintMessage=1
	Begin
		If @IfVip=1
			print 'VIP卡类型（0-会员价卡，1-折扣卡）：'+Cast(@VipCardType as varchar(2))
		Else
			print '未使用Vip卡'
		print 'VIP折扣：'+Cast(@VipDiscount as varchar(30))
		print '会员价：'+Cast(@VipPrice as varchar(30))
	End
	

	--取得系统配置跟踪策略
	Declare @MaxDate		varchar(10)	--最近日期
	Declare @IfgzPrice		int		--1：采用价格跟踪，0：不采用
	Declare @IfgzDiscount   	int		--1：采用折扣跟踪，0：不采用
	Declare @TraceBuyPrice		numeric(24,10)	--跟踪采购价
	Declare @TraceBuyDiscount	numeric(24,10)	--跟踪采购折扣
	Declare @TraceSalePrice		numeric(24,10)	--跟踪销售价
	Declare @TraceSaleDiscount	numeric(24,10)	--跟踪销售折扣
	Declare @TraceSendPrice		numeric(24,10)	--跟踪配货价
	Declare @TraceSendDiscount	numeric(24,10)	--跟踪配货折扣
	/*-------价格跟踪从系统配置移植到各个类型单据的业务配置下，且原折扣和价格跟踪合并成现在的统一一个价格跟踪设置---*/
	--Select @IfgzPrice = [stats] From  SysCon Where [order]=8
	--Select @IfgzDiscount = [stats] From  SysCon Where [order]=46	
	select @IfgzPrice=[stats],@IfgzDiscount=[stats] from syscon where [order]=case 
						when @vchtype in (6,7,34) then 211 
						when @vchtype in (8,11,24,45) then 212 
						when @vchtype in (211,212,218,221,222,223,224,234,232,230) then 214 
						else 0 end
	select @IfgzPrice=isnull(@IfgzPrice,0),@IfgzDiscount=isnull(@IfgzDiscount,0)
	/*-----------------END----------------*/

	--兼容销售启用价格跟踪（过滤机构）
	DECLARE @cboPriceTrackByBranch INT
	SELECT @cboPriceTrackByBranch = ISNULL((SELECT Stats FROM dbo.SysCon WHERE [Order] = 241),0)
	SELECT @cboPriceTrackByBranch
	

	If @IfgzPrice=1 or @IfgzDiscount=1	--价格、折扣跟踪
	Begin
		--取跟踪采购价、采购折扣
		Select @MaxDate= Max(BuyDate) From PriceTrace Where PtypeId=@PtypeId And BtypeId=@BtypeId And BranchId=@BranchId
		Select @TraceBuyPrice=IsNull(CostPrice,0),@TraceBuyDiscount=IsNull(BuyDiscount,0) From PriceTrace 
			Where Buydate=@MaxDate And PtypeId=@PtypeId And BtypeId=@BtypeId And BranchId=@BranchId
		--取跟踪销售价、销售折扣
		Select @MaxDate= Max(SaleDate) From PriceTrace Where PtypeId=@PtypeId And BtypeId=@BtypeId 
			And ((BranchId=@BranchId AND (@cboPriceTrackByBranch = 1 OR LEFT(@branchid,5) = '00004')) OR (@cboPriceTrackByBranch = 0 AND Btypeid LIKE '00002%'))
		Select @TraceSalePrice=IsNull(SalePrice,0),@TraceSaleDiscount=IsNull(SaleDiscount,0) From PriceTrace 
			Where SaleDate=@MaxDate And PtypeId=@PtypeId And BtypeId=@BtypeId 
			And ((BranchId=@BranchId AND (@cboPriceTrackByBranch = 1 OR LEFT(@branchid,5) = '00004')) OR (@cboPriceTrackByBranch = 0 AND Btypeid LIKE '00002%'))

		--取跟踪配货价、配货折扣
		--配货价相当怪异，其它价格BranchID写的是主体机构ID，而配货写的是入库机构ID
		Select @MaxDate= Max(SendDate) From PriceTrace Where PtypeId=@PtypeId And BranchId=@BtypeId
		Select @TraceSendPrice=IsNull(SendPrice,0),@TraceSendDiscount=IsNull(SendDiscount,0) From PriceTrace 
				Where SendDate=@MaxDate And PtypeId=@PtypeId And BranchId=@BtypeId
	End
	If @TraceBuyPrice Is Null
		Set @TraceBuyPrice=0
	If @TraceBuyDiscount Is Null
		Set @TraceBuyDiscount=0
	If @TraceSalePrice Is Null
		Set @TraceSalePrice=0
	If @TraceSaleDiscount Is Null
		Set @TraceSaleDiscount=0
	If @TraceSendPrice Is Null
		Set @TraceSendPrice=0
	If @TraceSendDiscount Is Null
		Set @TraceSendDiscount=0

	If @IsPrintMessage=1
	Begin
		print '跟踪采购价:'+Cast(@TraceBuyPrice as varchar(30))
		print '跟踪采购折扣:'+Cast(@TraceBuyDiscount as varchar(30))
		print '跟踪销售价:'+Cast(@TraceSalePrice as varchar(30))
		print '跟踪销售折扣:'+Cast(@TraceSaleDiscount as varchar(30))
		print '跟踪配货价:'+Cast(@TraceSendPrice as varchar(30))
		print '跟踪配货折扣:'+Cast(@TraceSendDiscount as varchar(30))
	End

	--取得往来单位预设价格
	Declare @BtypePrice	numeric(24,10)		--往来单位预设价格
	Declare @BtypeDiscount	numeric(24,10)		--往来单位预设折扣
	Set @BtypePrice=0
	Set @BtypeDiscount=0
	/*预设售价和预设折扣取消权限
	If Exists(Select 1 From PtypePrice pp,BtypeDistribute bd, FN_GetPowerRangePriceTypeList(@OperatorId) pt 
	Where bd.BtypeId=@BtypeId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.PriceTypeId And pp.PriceTypeId=pt.PriceTypeId)
		Select @BtypePrice=Price From PtypePrice pp,BtypeDistribute bd, FN_GetPowerRangePriceTypeList(@OperatorId) pt 
		Where bd.BtypeId=@BtypeId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.PriceTypeId And pp.PriceTypeId=pt.PriceTypeId
	If Exists(Select 1 From PtypePrice pp,BtypeDistribute bd, FN_GetPowerRangePriceTypeList(@OperatorId) pt  
	Where bd.BtypeId=@BtypeId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.DiscountTypeId And pp.PriceTypeId=pt.PriceTypeId)
		Select @BtypeDiscount=Price From PtypePrice pp,BtypeDistribute bd, FN_GetPowerRangePriceTypeList(@OperatorId) pt  
		Where bd.BtypeId=@BtypeId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.DiscountTypeId And pp.PriceTypeId=pt.PriceTypeId*/
	If Exists(Select 1 From PtypePrice pp,BtypeDistribute bd
	Where bd.BtypeId=@BtypeId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.PriceTypeId)
		Select @BtypePrice=Price From PtypePrice pp,BtypeDistribute bd
		Where bd.BtypeId=@BtypeId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.PriceTypeId
	If Exists(Select 1 From PtypePrice pp,BtypeDistribute bd
	Where bd.BtypeId=@BtypeId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.DiscountTypeId )
		Select @BtypeDiscount=Price From PtypePrice pp,BtypeDistribute bd
		Where bd.BtypeId=@BtypeId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.DiscountTypeId
	
	If @IsPrintMessage=1

	Begin
		print '往来单位预设价格:'+Cast(@BtypePrice as varchar(30))
		print '往来单位预设折扣:'+Cast(@BtypeDiscount as varchar(30))
	End

	/******************************************
	*   根据不同的单据类型，按规则取价格、折扣
	******************************************/
	Set @Price = 0
	Set @DiscountPrice = 0
	Set @Discount = 100
	If @IsPrintMessage=1 print '单据及取价规则:'
	--采购单取价规则 注：采购单价取值规则只与采购价格跟踪、供应预设采购价有关；
	if @VchType in (7,34,6)		
	Begin
		If @IsPrintMessage=1 print '采购单'
		If @IsPrintMessage=1 print '①系统时是否启用“往来单位价格跟踪”？'
		If @IfgzPrice=1
		Begin
			If @IsPrintMessage=1 print '是：商品是否有跟踪采购价？'
			If @TraceBuyPrice>0
			Begin
				If @IsPrintMessage=1 print '是：单价＝跟踪价　Go ②'
				Set @Price = @TraceBuyPrice
				Goto BuyBill2
			End
			Else
			Begin
				Goto BuyBill1
			End
		End
		Else
		Begin
			Goto BuyBill1
		End
		Goto BuyBillEnd

BuyBill1:
		If @IsPrintMessage=1 print '否：商品是否有供应商预设采购价？'
		If @BtypePrice>0
		Begin
			If @IsPrintMessage=1 print '是：单价＝供应商预设采购价   Go ②'
			Set @Price = @BtypePrice
			Goto BuyBill2
		End
		Else
		Begin
			If @IsPrintMessage=1 print '否：商品是否有零售价？'
			If @RetailPrice>0
			Begin
				If @IsPrintMessage=1 print '是：单价＝零售价    Go ②'
				Set @Price = @RetailPrice
				Goto BuyBill2
			End
			Else
			Begin
				If @IsPrintMessage=1 print '否：单价为空，由用户录入   Go ②'
				Set @Price = 0
				Goto BuyBill2
			End
		End
		Goto BuyBillEnd

BuyBill2:
		Set @Discount = 0
		If @IsPrintMessage=1 print '②系统是否启用“往来单位折扣跟踪”？'
		If @IfgzDiscount=1
		Begin
			If @IsPrintMessage=1 print '是：是否有跟踪采购折扣？'
			If @TraceBuyDiscount>0
			Begin
				If @IsPrintMessage=1 print '是：扣率＝跟踪折扣'
				Set @Discount = @TraceBuyDiscount
			End
			Else
			Begin
				If @IsPrintMessage=1 print '否：商品是否有供应商预设折扣？'
				If @BtypeDiscount>0
				Begin
					If @IsPrintMessage=1 print '是：扣率＝预设折扣'
					Set @Discount = @BtypeDiscount
				End
				Else
				Begin
					If @IsPrintMessage=1 print '否：扣率＝１'
					Set @Discount = 100
				End
			End
		End
		Else
		Begin
			If @IsPrintMessage=1 print '否：商品是否有供应商预设折扣？'
			If @BtypeDiscount>0
			Begin
				If @IsPrintMessage=1 print '是：扣率＝预设折扣'
				Set @Discount = @BtypeDiscount
			End
			Else
			Begin
				If @IsPrintMessage=1 print '否：扣率＝１'
				Set @Discount = 100
			End
		End
		--Set @DiscountPrice = Cast(@Price*@Discount/100 as Numeric(24,10))
		Set @DiscountPrice = Cast(@Price as numeric(24,10))*cast(@Discount as numeric(24,10))/100
BuyBillEnd:
	End

	--零售单及代销零售单取价
	if @VchType in (12,100)		
	Begin
		If @IsPrintMessage=1 print '零售单及代销零售单'
		If @IsPrintMessage=1 print '判断是否使用VIP会员价卡？'
		If @IfVip=1 And @VipCardType=0
		Begin
			If @IsPrintMessage=1 print '是：商品是否有对应机构零售价？'
			If @BranchRetailPrice > 0
			Begin
				If @IsPrintMessage=1 print '是：单价＝机构零售价，折后单价＝会员价，扣率＝折后单价/单价'
				Set @Price = @BranchRetailPrice
				Set @DiscountPrice = @VipPrice
				--Set @Discount = Cast(@DiscountPrice/@Price*100 as Numeric(24,2))
				Set @Discount = Cast(@DiscountPrice as numeric(24,10))/cast(@Price as numeric(24,10))*100
			End
			Else
			Begin	
				If @IsPrintMessage=1 print '否：商品是否有零售价？'
				If @RetailPrice>0
				Begin	
					If @IsPrintMessage=1 print '是:单价=商品零售价,折后单价=会员价，扣率＝折后单价/单价'
					Set @Price = @RetailPrice
					Set @DiscountPrice = @VipPrice
					--Set @Discount = Cast(@DiscountPrice/@Price*100 as Numeric(24,2))
					Set @Discount = cast(@DiscountPrice as numeric(24,10))/cast(@Price as numeric(24,10))*100
				End
				Else
				Begin
					If @IsPrintMessage=1 print '否:单价＝折后单价=会员价，扣率＝折后单价/单价'
					Set @Price = @VipPrice
					Set @DiscountPrice = @VipPrice
					Set @Discount = 100
				End
			End
		End
		Else
		Begin
			If @IsPrintMessage=1 print '否：商品是否有对应机构零售价？'
			If @BranchRetailPrice>0
			Begin
				If @IsPrintMessage=1 print '是：商品是否有对应机构零售扣率？'
				If @BranchRetailDiscount>0
				Begin
					If @IsPrintMessage=1 print '是:单价=机构零售价,扣率=机构零售扣率，折后单价=单价*扣率;'
					Set @Price = @BranchRetailPrice
					Set @Discount = @BranchRetailDiscount
					--Set @DiscountPrice = Cast(@Price*@Discount/100 as Numeric(24,4))
					Set @DiscountPrice = Cast(@Price as numeric(24,10))*cast(@Discount as numeric(24,10))/100
				End
				Else
				Begin
					If @IsPrintMessage=1 print '否：单价＝机构零售价＝折后单价，扣率＝1'
					Set @Price = @BranchRetailPrice
					Set @DiscountPrice = @BranchRetailPrice
					Set @Discount = 100
				End
			End
			Else
			Begin
				If @IsPrintMessage=1 print '否:商品是否有零售价?'
				If @RetailPrice>0
				Begin
					If @IsPrintMessage=1 print '是：商品是否有对应机构零售扣率？'
					If @BranchRetailDiscount>0
					Begin
						If @IsPrintMessage=1 print '是:单价=零售价,扣率=机构零售扣率，折后单价=单价*扣率;'
						Set @Price = @RetailPrice
						Set @Discount = @BranchRetailDiscount
						--Set @DiscountPrice = Cast(@Price*@Discount/100 as Numeric(24,4))
						Set @DiscountPrice = Cast(@Price as numeric(24,10))*cast(@Discount as numeric(24,10))/100
					End
					Else
					Begin
						If @IsPrintMessage=1 print '否：单价＝零售价＝折后单价，扣率＝1'
						Set @Price = @RetailPrice
						Set @DiscountPrice = @RetailPrice
						Set @Discount = 100
					End
				End
				Else
				Begin
					If @IsPrintMessage=1 print '否：单价为空由用户录入，扣率＝1'
					Set @Price = 0
					Set @DiscountPrice = 0
					Set @Discount = 100
				End
			End
		End

		If @VchType = 100
		Begin
			Select @Tax=TaxRate From BtypeDistribute bd, Branch bc
				Where bc.BranchId = @BranchId And Len(IsNull(bc.BtypeId,''))>0 And bc.BtypeId=bd.BtypeId
			Select @MarketDiscount=Price From PtypePrice pp,BtypeDistribute bd, FN_GetPowerRangePriceTypeList(@OperatorId) pt  
				Where exists(Select 1 From Branch Where BranchId = @BranchId And Len(IsNull(BtypeId,''))>0 And BtypeId=bd.BtypeId) 
				And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.MarketDiscountId And pp.PriceTypeId=pt.PriceTypeId
			If @IsPrintMessage=1
			Begin
				print '商场专柜零售单取商场扣率及税率'
				print '商场扣率：'+Cast(@MarketDiscount as varchar(30))
				print '商场税率：'+Cast(@Tax as varchar(30))
			End
		End
	End 
	
	--销售订单、销售单、销售退货单、销售退换货单	
	If @VchType in (8,11,45,24)
	Begin
		If @IsPrintMessage=1 print '销售单、销售退货单、销售退换货单'
		If @IsPrintMessage=1 print '判断是否使用VIP会员价卡？'
		If @IfVip=1 And @VipCardType=0
		Begin
			If @IsPrintMessage=1 print '是：商品是否有对客户预设售价？'
			If @BtypePrice>0
			Begin
				If @IsPrintMessage=1 print '是:单价=预设售价,折后单价=会员价，扣率＝折后单价/单价'
				Set @Price = @BtypePrice
				Set @DiscountPrice = @VipPrice
				--Set @Discount = Cast(@DiscountPrice/@Price*100 as Numeric(24,2))
				Set @Discount = Cast(@DiscountPrice as numeric(24,10))/cast(@Price as numeric(24,10))*100
			End
			Else
			Begin
				If @IsPrintMessage=1 print '否:商品是否有零售价?'
				If @RetailPrice>0
				Begin
					If @IsPrintMessage=1 print '是:单价=商品零售价,折后单价=会员价，扣率＝折后单价/单价'
					Set @Price = @RetailPrice
					Set @DiscountPrice = @VipPrice
					--Set @Discount = Cast(@DiscountPrice/@Price*100 as Numeric(24,2))	
					Set @Discount = Cast(@DiscountPrice as numeric(24,10))/cast(@Price as numeric(24,10))*100
				End
				Else
				Begin
					If @IsPrintMessage=1 print '否:单价＝折后单价=会员价，扣率＝1'
					Set @Price = @VipPrice
					Set @DiscountPrice = @VipPrice
					Set @Discount = 100
				End
			End
		End
		Else
		Begin
			If @IsPrintMessage=1 print '否：系统时是否启用“往来单位价格跟踪”？'
			If @IfgzPrice=1
			Begin
				If @IsPrintMessage=1 print '是：商品是否有跟踪价？'
				If @TraceSalePrice>0
				Begin
					If @IsPrintMessage=1 print '是：单价＝跟踪价　Go ②'
					Set @Price = @TraceSalePrice
					Goto SaleBill2
				End
				Else
				Begin
					Goto SaleBill1
				End
			End
			Else
			Begin
				Goto SaleBill1
			End
		End
		Goto SaleBillEnd

SaleBill1:
		If @IsPrintMessage=1 print '否：商品是否有客户预设售价？'
		If @BtypePrice>0
		Begin
			If @IsPrintMessage=1 print '是：单价＝客户预设售价   Go ②'
			Set @Price = @BtypePrice
			Goto SaleBill2
		End
		Else
		Begin
			If @IsPrintMessage=1 print '否：商品是否有零售价？'
			If @RetailPrice>0
			Begin
				If @IsPrintMessage=1 print '是：单价＝零售价    Go ②'
				Set @Price = @RetailPrice
				Goto SaleBill2
			End
			Else
			Begin
			
				If @IsPrintMessage=1 print '否：单价为空，由用户录入   Go ②'
				Set @Price = 0
				Goto SaleBill2
			End
		End
		Goto SaleBillEnd

SaleBill2:
		Set @Discount = 0
		If @IsPrintMessage=1 print '②系统是否启用“往来单位折扣跟踪”？'
		If @IfgzDiscount=1
		Begin
			If @IsPrintMessage=1 print '是：是否有跟踪折扣？'
			If @TraceSaleDiscount>0
			Begin
				If @IsPrintMessage=1 print '是：扣率＝跟踪折扣'
				Set @Discount = @TraceSaleDiscount
			End
			Else
			Begin
				If @IsPrintMessage=1 print '否：商品是否有客户预设折扣？'
				If @BtypeDiscount>0
				Begin
					If @IsPrintMessage=1 print '是：扣率＝预设折扣'
					Set @Discount = @BtypeDiscount
				End
				Else
				Begin
					If @IsPrintMessage=1 print '否：扣率＝１'
					Set @Discount = 100
				End
			End
		End
		Else
		Begin
			If @IsPrintMessage=1 print '否：商品是否有客户预设折扣？'
			If @BtypeDiscount>0
			Begin
				If @IsPrintMessage=1 print '是：扣率＝预设折扣'
				Set @Discount = @BtypeDiscount	
			End
			Else
			Begin
				If @IsPrintMessage=1 print '否：扣率＝１'
				Set @Discount = 100
			End
		End
		--Set @DiscountPrice = Cast(@Price*@Discount/100 as Numeric(24,4))
		Set @DiscountPrice = Cast(@Price as numeric(24,10))*cast(@Discount as numeric(24,10))/100
SaleBillEnd:			
	End

	--加盟商配货订单、配货单(总部)、退货申请单、退货单（总部）、配货单（加）、退货单（加）'
	If @VchType in (221,222,223,234) 	--加盟商配货单取价规则 注：加盟商配货单价取值规则与“价格折扣跟踪”、与机构配货价有关；
	Begin
		If @IsPrintMessage=1 print '加盟商配货订单、配货单、配货退货单'
		If @IsPrintMessage=1 print '①系统时是否启用“往来单位价格跟踪”？'
		If @IfgzPrice=1
		Begin
			If @IsPrintMessage=1 print '是：商品是否有跟踪配货价？'
			If @TraceSendPrice>0
			Begin
				If @IsPrintMessage=1 print '是：单价＝跟踪价　Go ②'
				Set @Price = @TraceSendPrice
				Goto RationBill2
			End
			Else
			Begin
				Goto RationBill1
			End
		End
		Else
		Begin
			Goto RationBill1
		End
		Goto RationBillEnd

RationBill1:
		If @IsPrintMessage=1 print '否：商品是否有机构配货预设售价？'
		If @BranchRationPrice>0
		Begin
			If @IsPrintMessage=1 print '是：单价＝预设售价   Go ②'
			Set @Price = @BranchRationPrice
			Goto RationBill2
		End
		Else
		Begin
			If @IsPrintMessage=1 print '否：商品是否有零售价？'
			If @RetailPrice>0
			Begin
				If @IsPrintMessage=1 print '是：单价＝零售价   Go ②'
				Set @Price = @RetailPrice
				Goto RationBill2
			End
			Else
			Begin
				If @IsPrintMessage=1 print '否：单价为空，由用户录入 Go ②'
				Set @Price = 0
				Goto RationBill2
			End
		End
		Goto RationBillEnd

RationBill2:
		Set @Discount = 0
		If @IsPrintMessage=1 print '②系统是否启用“往来单位折扣跟踪”？'
		If @IfgzDiscount=1
		Begin
			If @IsPrintMessage=1 print '是：是否有跟踪配货折扣？'
			if @TraceSendDiscount>0
			Begin
				If @IsPrintMessage=1 print '是：扣率＝跟踪折扣'
				Set @Discount = @TraceSendDiscount
			End
			Else
			Begin
				If @IsPrintMessage=1 print '否：商品是否有机构预设配货折扣？'
				If @BranchRationDiscount>0
				Begin
					If @IsPrintMessage=1 print '是：扣率＝预设折扣'
					Set @Discount = @BranchRationDiscount
				End
				Else
				Begin
					If @IsPrintMessage=1 print '否：扣率＝１'
					Set @Discount = 100
				End
			End
		End
		Else
		Begin
			If @IsPrintMessage=1 print '否：商品是否有机构预设配货折扣？'
			If @BranchRationDiscount>0
			Begin
				If @IsPrintMessage=1 print '是：扣率＝预设折扣'
				Set @Discount = @BranchRationDiscount
			End
			Else
			Begin
				If @IsPrintMessage=1 print '否：扣率＝１'
				Set @Discount = 100
			End
		End
		--Set @DiscountPrice = Cast(@Price*@Discount/100 as Numeric(24,4))
		Set @DiscountPrice = Cast(@Price as numeric(24,10))*cast(@Discount as numeric(24,10))/100
RationBillEnd:
	End


	--变价配货单取价规则 注：变价配货单价取值规则只与机构配货价有关；
	If @VchType in (212,211)
	Begin
		If @IsPrintMessage=1 print '变价配货单'
		If @IsPrintMessage=1 print '商品是否有对应机构预设配货价？'
		If @BranchRationPrice>0
		Begin
			If @IsPrintMessage=1 print '是：单价＝预设配货价'
			Set @Price = @BranchRationPrice
		End
		Else
		Begin
			If @IsPrintMessage=1 print '否：商品是否有对应零售价？'
			If @RetailPrice>0
			Begin
				If @IsPrintMessage=1 print '是：单价＝零售价'
				Set @Price = @RetailPrice
			End
			Else
			Begin
				If @IsPrintMessage=1 print '否：单价为空由用户录入'
				Set @Price = 0
			End
		End
			
		If @IsPrintMessage=1 print '商品是否有对应机构预设折扣？'
		--If @BranchRationDiscount>0
		--Begin
		--	If @IsPrintMessage=1 print '是：折扣＝预设折扣'
		--	Set @Discount = @BranchRationDiscount
		--End
		--Else
		--Begin
			If @IsPrintMessage=1 print '否：折扣＝１'
			Set @Discount = 100
		--End
		--Set @DiscountPrice = Cast(@Price*@Discount/100 as Numeric(24,4))		
		Set @DiscountPrice = Cast(@Price as numeric(24,10))*cast(@Discount as numeric(24,10))/100
	End

	--同价调拨单、同价配货单，单价取库存成本价
	If @Vchtype in (17,218)
	Begin
		select @price = price from goodsstocks where ptypeid=@ptypeid and ktypeid=@ktypeid
		If @IsPrintMessage=1 print '单价=库存成本价'+cast(@Price as varchar(30)) 
		
		select @discount = 100,@DiscountPrice=@price
	End
	
	If @IsPrintMessage=1
	Begin
		print ''
		print '取价结果：'
		print '折前单价：'+Cast(@Price as varchar(30))
		print '折扣：'+Cast(@Discount as varchar(30))
		print '折后单价：'+Cast(@DiscountPrice as varchar(30))
	End
	
	If @VchType in (251,252)
		Set @Price = @CostPrice
	
	Set @Price 		= IsNull(@Price,0)
	Set @Discount 		= IsNull(@Discount,100)
	Set @DiscountPrice	= IsNull(@DiscountPrice,0)
	If (@VchType in (212,218))
		Begin
			if exists(select Price From PtypePrice pp,BtypeDistribute bd, FN_GetPowerRangePriceTypeList(@OperatorId) pt 
			Where bd.Type=0 And bd.BranchId=@BtypeId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.PriceTypeId And pp.PriceTypeId=pt.PriceTypeId)
				begin
				select @BranchRetailPrice = Price From PtypePrice pp,BtypeDistribute bd, FN_GetPowerRangePriceTypeList(@OperatorId) pt 
				Where bd.Type=0 And bd.BranchId=@BtypeId And pp.PtypeId=@PtypeId And pp.PriceTypeId=bd.PriceTypeId And pp.PriceTypeId=pt.PriceTypeId
					if cast(@BranchRetailPrice as numeric(24,10))=0
						Set @RetailPrice= IsNull(@RetailPrice,0)
					else 
						Set @RetailPrice= isnull(@BranchRetailPrice,0)
				end
			Else
				Set @RetailPrice= isnull(@RetailPrice,0)
		End
	Else
		Set @RetailPrice= IsNull(@RetailPrice,0)
	Set @CostPrice = IsNull(@CostPrice,0)
	Set @VipDiscount = IsNull(@VipDiscount,100)
	
	--vip折扣规则,这里需要所有折扣及价格都取出之后才能做对比
	if @IfVip=1 and @VipCardType=1 and @VipDisCountMode=0	--最低折,则取较小的折扣，大的折扣为100
	begin
		if @VipDiscount<@Discount
		begin
			Set @Discount=100
			set @DiscountPrice=@Price
		end
		else
			set @VipDiscount=100
	end
	if @IfVip=1 and @VipCardType=1 and @VipDisCountMode=2	--VIP折扣，则取VIP折扣，商品折扣无效
	begin
		Set @Discount=100
		set @DiscountPrice=@Price
	end
	
	--END---折上折或其他不处理,保持原样
		
		
	Set @MarketDiscount = IsNull(@MarketDiscount,0)
	Set @Tax = IsNull(@Tax,0)
	
	--取小数精度
	DECLARE  @dig_qty int,@dig_price int,@dig_total int ,@dig_dis int ,@dig_tax int ,@dig_rate int 
	EXEC GetDig @dig_qty output ,@dig_price output,@dig_total output ,@dig_dis output ,@dig_tax output ,@dig_rate output
	
	set @Price = round(@Price,@dig_price)
	set @Discount = round(@Discount,@dig_dis)
	set @DiscountPrice = round(@DiscountPrice,@dig_price)
	set @RetailPrice = round(@RetailPrice,@dig_price)
	set @CostPrice = round(@CostPrice,@dig_price)
	set @VipDiscount = round(@VipDiscount,@dig_dis)
	set @MarketDiscount = round(@MarketDiscount,@dig_rate)
	set @Tax = round(@Tax,@dig_tax)	

	return 0
Err:
	return -1




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

